我想要一个 main_func
返回 T
类型的向量带有 SrObject
的结构性状
struct TestA {
value: u8,
}
pub trait SrObject {
fn myfunc(&mut self);
}
impl SrObject for TestA {
fn myfunc(&mut self) {
unimplemented!();
}
}
impl Default for TestA {
fn default() -> TestA {
TestA { value: 3u8 }
}
}
fn main_func<T: SrObject>(t: T) -> Vec<T> {
let mut v = Vec::<T>::new();
for i in 0..10 {
v.push(T::default());
//v[i].myfunc();
}
return v;
}
它给出:
error[E0599]: no function or associated item named `default` found for type `T` in the current scope
--> src/main.rs:22:16
|
22 | v.push(T::default());
| ^^^^^^^^^^ function or associated item not found in `T`
|
= help: items from traits can only be used if the trait is implemented and in scope
= note: the following trait defines an item `default`, perhaps you need to implement it:
candidate #1: `std::default::Default`
我知道我没有 Default
fn 中的特征 main_func<T: SrObject>
, 但我怎样才能在不删除 SrObject
的情况下实现这一目标特质?
最佳答案
我鼓励你回去重读 The Rust Programming Language .这是 Rust 社区创建的一本免费在线书籍,涵盖了成为一名成功的 Rust 程序员所需了解的广泛内容。
在这种情况下,chapter on traits提到这个关于 trait bounds :
We can specify multiple trait bounds on a generic type by using
+
. If we needed to be able to use display formatting on the typeT
in a function as well as thesummary
method, we can use the trait boundsT: Summarizable + Display
. This meansT
can be any type that implements bothSummarizable
andDisplay
.
针对您的情况:
fn main_func<T: SrObject + Default>() -> Vec<T> {
(0..10).map(|_| T::default()).collect()
}
或者
fn main_func<T>() -> Vec<T>
where
T: SrObject + Default,
{
(0..10).map(|_| T::default()).collect()
}
使其符合惯用语的其他更改:
- 调用
Vec::new
时不要指定v
的类型;它将被推断出来。 - 不要在函数末尾使用明确的
return
。 - 使用
Iterator::map
和Iterator::collect
将迭代器转换为集合,而不是手动推送元素。
另见:
关于generics - 一个函数如何要求一个类型实现一个特征而不删除现有的特征边界?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50180069/