Warning
This post was published 98 days ago. The information described in this article may have changed.
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
🏷️ rust_feed