Rust 使用泛型类型的运算符时出错
我正在学习rust,我不明白为什么下面的代码会出现错误Rust 使用泛型类型的运算符时出错,rust,Rust,我正在学习rust,我不明白为什么下面的代码会出现错误 use std::ops::Mul; use std::ops::Add; struct Vec2<T> { x: T, y: T, } impl<T: Mul + Add> Vec2<T> { fn magnitude_squared(&self) -> T { self.x * self.x + self.y * self.y // error
use std::ops::Mul;
use std::ops::Add;
struct Vec2<T>
{
x: T,
y: T,
}
impl<T: Mul + Add> Vec2<T> {
fn magnitude_squared(&self) -> T {
self.x * self.x + self.y * self.y // error here
}
}
fn main() {
let x = Vec2 { x: 1f32, y: 1f32 };
println!("{}", x.magnitude_squared());
}
使用std::ops::Mul;
使用std::ops::Add;
结构向量2
{
x:T,
y:T,
}
impl-Vec2{
fn震级_平方(&self)->T{
self.x*self.x+self.y*self.y//此处出错
}
}
fn main(){
设x=Vec2{x:1f32,y:1f32};
println!(“{}”,x.幅值_平方();
}
错误消息(除非两个浮点数相乘产生某种“不可添加”类型,否则对我来说没有多大意义):
src\main.rs(14,9):错误E0369:无法应用二进制操作+
键入::输出
帮助:运行rustc--explain E0369
查看详细说明
注意:对于::Output
Rust编译器rustc 1.11.0(9b21dcd6a 2016-08-15)
代码类似于示例。使我的代码出错的区别是什么?错误消息告诉您要做什么:您需要为::输出添加的添加实现
您可以通过在impl
上添加特征绑定来实现:
use std::ops::Mul;
use std::ops::Add;
struct Vec2<T: Copy>
{
x: T,
y: T,
}
impl<T> Vec2<T>
where T: Copy + Mul,
<T as Mul>::Output: Add<Output=T>
{
fn magnitude_squared(&self) -> T {
self.x * self.x + self.y * self.y
}
}
fn main() {
let x = Vec2 { x: 1f32, y: 1f32 };
println!("{}", x.magnitude_squared());
}
使用std::ops::Mul;
使用std::ops::Add;
结构向量2
{
x:T,
y:T,
}
impl-Vec2
其中T:Copy+Mul,
::输出:添加
{
fn震级_平方(&self)->T{
self.x*self.x+self.y*self.y
}
}
fn main(){
设x=Vec2{x:1f32,y:1f32};
println!(“{}”,x.幅值_平方();
}
添加副本
是为了简化这个答案。我认为在您的解决方案中,T*T
可能是一种完全不同的类型M
,只要将两个M
加在一起,就会再次得到T
。@ChrisEmerson:是的,你说得对。说ReST编译器在替换前是否进行类型检查是正确的,因此必须明确地指定特性类型的特征吗?(希望我的措辞有意义)。是的,不像C++,RIST要求我们在泛型函数中指定泛型类型的特性,以使用这些特征的方法。