Why is it possible to modify "self" without making it mut

⚓ rust    📅 2025-05-14    👤 surdeus    👁️ 3      

surdeus

In the following code from rustlngs, we are able to change self without making self as mutable. I wonder why this is even allowed by Rust compiler:

trait AppendBar {
    fn append_bar(self) -> Self;
}

impl AppendBar for String {
    // compiler allow us to change the value of self, even the parameter is not "mut self"
    fn append_bar(self) -> Self {
        self + "Bar"
    }
}

fn main() {
    let s = String::from("Foo");
     let s = s.append_bar();
    println!("s: {s}");
    
}

4 posts - 3 participants

Read full topic

🏷️ rust_feed