Reputation: 51
I'm trying to learn rust via rustlings and I'm encountering this weird error. I understand that it modifies self in place but why does it return a unit () instead of the modified String
impl AppendBar for String {
// TODO: Implement `AppendBar` for type `String`.
fn append_bar(self) -> Self {
self.push_str(" bar")
}
}
I tried to contain it in a variable first but I still get the same error. I was expecting that this would avoid a unit () return type.
impl AppendBar for String {
// TODO: Implement `AppendBar` for type `String`.
fn append_bar(self) -> Self {
let mut contain = self;
contain.push_str(" bar")
}
}
Upvotes: 2
Views: 1154
Reputation: 1
Sir, "I tried to contain it in a variable" Why? The altered variable itself can be used. If you want both will this not do?
fn main() {
let t = "abc".to_string();
let mut s = "abc".to_string();
s.push_str("def");
println!("t = {t};; s = {s}");
}
/* t = abc;; s = abcdef */
Upvotes: -2
Reputation: 421
Something like this?
impl AppendBar for String {
fn append_bar(mut self) -> Self {
self.push_str(" bar");
self
}
}
The String::push_str
function don't return anything, it mutates the String in place.
So you will you need to mutate the self and return it, in two separated statements.
Upvotes: 5