Search code examples
rustrust-rustlings

Method `push_str` returns () instead of String


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")
    }
}

Solution

  • 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.