Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why an implement of immutable trait can be mutable?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading