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) {}
}
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.
for std::vec::Vec:
fn into_boxed_slice(self) -> Box<[T]>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With