[英]How can a function require that a type implement a trait without removing the existing trait bound?
我正在嘗試使main_func
返回具有SrObject
特征的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`
我了解我在fn main_func<T: SrObject>
沒有Default
trait,但是如何在不刪除SrObject
trait的情況下實現這一SrObject
?
我鼓勵您回去重讀Rust編程語言 。 這是Rust社區創建的免費在線書籍,涵蓋了成為一名成功的Rust程序員所需了解的廣泛知識。
我們可以使用
+
在通用類型上指定多個特征范圍。 如果我們需要能夠在函數和summary
方法中使用類型T
上的顯示格式,則可以使用特征范圍T: Summarizable + Display
。 這意味着T
可以是實現Summarizable
和Display
任何類型。
對於您的情況:
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
將迭代器轉換為集合,而不是手動推送元素。 也可以看看:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.