traits2.rs Function Equivalence #2354
Replies: 2 comments
-
|
Great question, this confused me when I first encountered it too. The From the caller's perspective, both of these are identical: fn append_bar(self) -> Self // caller passes owned value
fn append_bar(mut self) -> Self // same, mut is invisible to the callerThe type is fn foo(x: i32) {}
fn bar(mut x: i32) { x = 42; } // same signature as fooBoth have type So |
Beta Was this translation helpful? Give feedback.
-
|
This works because in Rust, mut in a function parameter only affects how the value can be used inside the function, not its type. Trait definition: Adding mut in the implementation is purely for internal mutability; it does not change the method signature. Think of mut self as: "I own this value and can modify it before returning it." Whenever a trait method takes self by value, the implementer can declare it mut if they need to change it internally. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
In the traits2.rs solution, the function signature for append_bar differs between the
traitdefinition and theVec<String>implementation.Why does this compile if the function signatures differ?
My understanding is that because the function is not taking a reference, that the
mutkeyword is stating thatselfis mutable within the function. This seems to offer an additional level of freedom compared to thetraitsignature which states thatselfis NOT mutable.In this case how can these two function be considered equivalent?
Beta Was this translation helpful? Give feedback.
All reactions