Generics 返回通用向量
假设我有这样一个结构:Generics 返回通用向量,generics,struct,rust,traits,Generics,Struct,Rust,Traits,假设我有这样一个结构: struct A { field0: u32, field1: Vec<B>, } struct B { field0: f64, field1: String, field2: Vec<C>, } struct C { field0: Vec<u8>, field1: bool, } 结构A{ 字段0:u32, 字段1:Vec, } 结构B{ 字段0:f64, 字段1:字符
struct A {
field0: u32,
field1: Vec<B>,
}
struct B {
field0: f64,
field1: String,
field2: Vec<C>,
}
struct C {
field0: Vec<u8>,
field1: bool,
}
结构A{
字段0:u32,
字段1:Vec,
}
结构B{
字段0:f64,
字段1:字符串,
字段2:Vec,
}
结构C{
字段0:Vec,
字段1:布尔,
}
我想为每个结构实现一个trait,它输出一个包含Vec的字段
// snip
trait MyVec<T> {
fn myvec(&self) -> Vec<T>;
}
impl MyVec<T> for A {
fn myvec(&self) -> Vec<T> { // return Vec<B>
&self.field1
}
}
impl MyVec<T> for B {
fn myvec(&self) -> Vec<T> { // return Vec<C>
&self.field2
}
}
impl MyVec<T> for C {
fn myvec(&self) -> Vec<T> { // return Vec<u8>
&self.field0
}
}
//snip
性状MyVec{
fn myvec(&self)->Vec;
}
将MyVec用于{
fn myvec(&self)->Vec{//返回Vec
&self.field1
}
}
B的impl MyVec{
fn myvec(&self)->Vec{//返回Vec
&self.field2
}
}
impl MyVec for C{
fn myvec(&self)->Vec{//返回Vec
&self.field0
}
}
但编译器抱怨需要类型参数T,但找到了结构B
。我如何正确地做到这一点
很抱歉,如果这是一个愚蠢的问题,我对锈菌很陌生,对泛型或特性一无所知。您需要指定
t
。i、 e:
impl MyVec<B> for A {
fn myvec(&self) -> Vec<B> {
&self.field1
}
}
trait MyVec {
type Item;
fn myvec(&self) -> Vec<Self::Item>;
}
impl MyVec for A {
type Item = B;
fn myvec(&self) -> Vec<B> {
&self.field1
}
}