Here is my code, it can compile
trait AppendBar {
fn append_bar(self) -> Self;
}
impl AppendBar for Vec<String> {
fn append_bar(mut self) -> Self {
self.push("Bar".to_string());
self
}
although it takes the ownership, but why it can mutate self in its implementation?
Because mutability of arguments is not part of the function signature.
This ...
fn foo(self) { ... }
... looks exactly the same from the outside as ...
fn foo(mut self) { ... }
... because it's not the caller's business what happens with the arguments once control transfers to the function.
Therefore, the implementation of the trait is allowed because the signature is effectively the same from the perspective of the caller.
Put another way, what is the difference between these two functions?
fn foo(mut v: String) {
// ...
}
fn foo(v: String) {
let mut v = v; // Rebind v as mutable.
// ...
}
The answer is that there is none. The String
value was given to the function, so it can always mutate it. If it helps you to understand what is going on, you could consider the first example to be a "shortcut" for the second, but they wind up meaning the same thing.
Note this is not a unique thing to Rust; in C++, const
-ness of function arguments is not part of the function's signature, either.