HarrisonG16
HarrisonG16

Reputation: 903

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

I'm looking to do something similar to the following: pass the 'self' value in hope of getting the method I'm calling (get_dot) to access the values x and y. However, there is a type mismatch and I'm unsure whether I need to dereference it or something else. Here's an example in which I pass @ or this in CoffeeScript and the other method is able to access its values properly:

class Testing
  constructor: -> @x = 10

  doSomething: (value) ->
    return @x * value.x

  doSomething2: () ->
    @doSomething(@)

y = new Testing()
alert(y.doSomething2()) //100

My actual Rust code looks like:

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!
    }
}

I get the following error:

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

Upvotes: 1

Views: 94

Answers (1)

fjh
fjh

Reputation: 13081

There is a 1-character fix for your code:

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()
    }
}

The problem is that your get_dot method takes its second argument by value instead of by reference. This is unnecessary (since the method does not need to own that argument, just be able to access it) and it cannot actually work if you want to call it like you do in get_magnitude.

Upvotes: 4

Related Questions