Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to pass self as a reference for methods?

Tags:

rust

I understand the ownership differences that come with passing by value vs passing by reference, but I'm struggling with this when passing around self. When do I want self to not be a reference?

struct Test {}

impl Test {
    fn my_method(&self) {}
}
like image 546
Taztingo Avatar asked Nov 26 '25 17:11

Taztingo


1 Answers

Don't think too much. If we ignore subtyping polymorphism, we can tread all the object-oriented style "method invocation" as a "function invocation", by converting a.b(c) into b(a, c) inside your brain.

So, since you have

struct Test { }
impl Test { fn my_method(&self) { } }

my_method is simply a function that takes one argument, and when you invoke it like testInstance.my_method(), it's actually my_method(testInstance), and testInstance is passed as self.

So it's all the same with other functions.
Think about when do you want a simple function parameter not to be a reference, and that's the question to your answer.

Example

for std::vec::Vec:

fn into_boxed_slice(self) -> Box<[T]>
like image 143
ice1000 Avatar answered Nov 28 '25 16:11

ice1000



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!