想要有一个通用类型的正方形结构体,然后通过impl找到面积?


struct Sqr<T> {
len: T,
// wid: T,
}
impl<T> Sqr<T> {
fn mult(self, other: Sqr<T>) -> T {
self.len * other.len // error here.
// error is : cannot multiply `T` to `T`
}
}

自我。len是T型变量,如何将两个T型变量相加或相乘?

在代码中,将两个泛型类型为T的变量相乘,但是它们可能不实现乘法的multi特性。因此,您需要显式地要求它们实现multi特性,如下所示:

impl<T> Sqr<T> where
T: std::ops::Mul<T, Output = T> {
fn mult(self, other: Sqr<T>) -> T {
self.len * other.len 
}
}

关于这个主题的更多信息,你可以参考Rust By Example的" generic "chapter -特别是Bounds

相关内容

最新更新