Types 我得到了一个预期的类型参数,尽管我认为我已经返回了正确的类型数据

Types 我得到了一个预期的类型参数,尽管我认为我已经返回了正确的类型数据,types,rust,traits,Types,Rust,Traits,我得到了一个预期的类型参数,尽管我认为我已经返回了正确的类型数据。我正在学习rust中的通用材料 struct Cat { weight: i32, } trait Animal{ fn get_weight<T>(&self) -> T; } impl Animal for Cat { fn get_weight<i32>(&self) -> i32 { self.weight // I got e

我得到了一个预期的类型参数,尽管我认为我已经返回了正确的类型数据。我正在学习rust中的通用材料

struct Cat {
    weight: i32,
}

trait Animal{
    fn get_weight<T>(&self) -> T;
}

impl Animal for Cat {
    fn get_weight<i32>(&self) -> i32 {
        self.weight // I got error in here
    }
}

fn main() {}

在这里查看编译器警告非常有用

warning: type parameter `i32` should have an upper camel case name
  --> src/main.rs:10:19
   |
10 |     fn get_weight<i32>(&self) -> i32 {
   |                   ^^^ help: convert the identifier to upper camel case: `I32`
   |
   = note: #[warn(non_camel_case_types)] on by default
请注意,
T
与trait一起引入,而不是在方法上引入。通过这种设置,您在概念上不再有单一的特征,而是每种类型都有一个特征(同样是隐式
size
bounds)。这意味着给定的类型可以为不同的
T
值实现特征。您可能已经为
Cat
实现了
Animal
Animal

如果您仍然希望每个类型只实现trait一次,并且只有一个输出类型,那么可以使用关联的类型。其语法是

trait Animal<T> {
    fn get_weight(&self) -> T;
}
trait Animal{
    type Weight;

    fn get_weight(&self) -> Self::Weight;
}
现在,当您在类型上实现这个特性时,您必须提供输出类型。您可以通过添加行
type Weight=i32来实现
Cat
。然后,
get\u weight
方法只需返回
i32
,就像您已经得到的一样

trait Animal{
    type Weight;

    fn get_weight(&self) -> Self::Weight;
}