我正在寻找与以下类似的方法:传递“自我”值,以期获得我正在调用(get_dot
)的方法来访问值x
和y
。但是,存在类型不匹配,并且我不确定是否需要取消引用它或其他。这是一个示例,其中我通过@
或this
在CoffeeScript中通过,另一种方法能够正确访问其值:
class Testing
constructor: -> @x = 10
doSomething: (value) ->
return @x * value.x
doSomething2: () ->
@doSomething(@)
y = new Testing()
alert(y.doSomething2()) //100
我实际的Rust代码如下所示:
struct Vec2 {
x: f32,
y: f32,
}
impl Vec2 {
// Other stuff
fn get_dot(&self, right: Vec2) -> f32 {
self.x * right.x + self.y * right.y
}
fn get_magnitude(&self) -> f32 {
(self.get_dot(self)).sqrt() // Problematic line!
}
}
我收到以下错误:
src/vec2.rs:86:23: 86:27 error: mismatched types:
expected `Vec2`,
found `&Vec2`
(expected struct `Vec2`,
found &-ptr) [E0308]
src/vec2.rs:86 (self.get_dot(self)).sqrt()
^~~~
error: aborting due to previous error
您的代码有一个1个字符的修复程序:
struct Vec2 {
x: f32,
y: f32,
}
impl Vec2 {
// Other stuff
fn get_dot(&self, right: &Vec2) -> f32 { // note the type of right
self.x * right.x + self.y * right.y
}
fn get_magnitude(&self) -> f32 {
(self.get_dot(self)).sqrt()
}
}
问题在于您的get_dot
方法通过值而不是通过引用来接受第二个参数。这是不必要的(因为该方法不需要拥有该参数,只需能够访问它即可),并且如果您想像在in中那样调用它,则它实际上无法工作get_magnitude
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句