如何将一个方法的'self'值传递给另一个方法?

How to pass the 'self' value of a method to another method?

我想做类似于以下的事情:传递 'self' 值,希望获得我正在调用的方法 (get_dot) 来访问值 xy。但是,存在类型不匹配,我不确定是否需要取消引用它或其他东西。这是我在 CoffeeScript 中传递 @this 的示例,另一种方法能够正确访问其值:

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 方法按值而不是按引用获取第二个参数。这是不必要的(因为该方法不需要拥有该参数,只需能够访问它)并且如果您想像在 get_magnitude.

中那样调用它,它实际上无法工作