Appearance
Trait5: exercises/traits/traits5.rs
题目
rust
// traits5.rs
//
// Your task is to replace the '??' sections so the code compiles.
//
// Don't change any line other than the marked one.
//
// Execute `rustlings hint traits5` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE
pub trait SomeTrait {
fn some_function(&self) -> bool {
true
}
}
pub trait OtherTrait {
fn other_function(&self) -> bool {
true
}
}
struct SomeStruct {}
struct OtherStruct {}
impl SomeTrait for SomeStruct {}
impl OtherTrait for SomeStruct {}
impl SomeTrait for OtherStruct {}
impl OtherTrait for OtherStruct {}
// YOU MAY ONLY CHANGE THE NEXT LINE
fn some_func(item: ??) -> bool {
item.some_function() && item.other_function()
}
fn main() {
some_func(SomeStruct {});
some_func(OtherStruct {});
}
您的任务是替换??
部分的代码,以便代码通过编译。
除了标记行以外,不要有任何的修改行为。
题目解析
由于在some_func
函数中,item
既调用了some_function
方法,也调用了other_function
方法,所以我们需要要求item
实现SomeTrait
和OtherTrait
两个Trait。
为了确保参数实现多个Trait,可以使用+
语法。
rust
fn some_func(item: ??) -> bool {
fn some_func(item: impl SomeTrait + OtherTrait) -> bool {
item.some_function() && item.other_function()
}