我做了一个两元素Vector结构,我想重载+运算符.
我使我的所有函数和方法都采用引用而不是值,我希望+运算符以相同的方式工作.
impl Add for Vector {
fn add(&self, other: &Vector) -> Vector {
Vector {
x: self.x + other.x,
y: self.y + other.y,
}
}
}
Run Code Online (Sandbox Code Playgroud)
根据我尝试的变化,我要么遇到生命问题,要么输入不匹配.具体来说,这个&self论点似乎没有被视为正确的类型.
我已经看到了模板参数的例子上impl,以及Add,但他们只是导致不同的错误.
我发现如何为不同的RHS类型和返回值重载运算符?但即使我把一个use std::ops::Mul;放在顶部,答案中的代码也不起作用.
我正在使用rustc 1.0.0-nightly(ed530d7a3 2015-01-16 22:41:16 +0000)
我不接受"你只有两个字段,为什么要使用参考"作为答案; 如果我想要一个100元素结构怎么办?我会接受一个答案,证明即使有一个大的结构我也应该通过值传递,如果是这样的话(我认为不是这样).我有兴趣知道结构大小的一个好的经验法则并且通过值vs struct传递,但这不是当前的问题.
我有一个枚举:
enum Foo {
Bar = 1,
}
Run Code Online (Sandbox Code Playgroud)
如何将对此枚举的引用转换为要在数学中使用的整数?
fn f(foo: &Foo) {
let f = foo as u8; // error[E0606]: casting `&Foo` as `u8` is invalid
let f = foo as &u8; // error[E0605]: non-primitive cast: `&Foo` as `&u8`
let f = *foo as u8; // error[E0507]: cannot move out of borrowed content
}
Run Code Online (Sandbox Code Playgroud)