0

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")
    }
}
oguz ismail
  • 1
  • 16
  • 47
  • 69
Starfish
  • 31
  • 3
  • 2
    Because `push_str` doesn't return anything. If you want to return `Self`, then do it. – tkausl Dec 27 '22 at 17:23
  • Are you asking "why" as in "why was it designed so" in which case it should be closed as opinion based, or something else? – Chayim Friedman Dec 27 '22 at 17:23
  • Hint: `; self` in that function. – tadman Dec 27 '22 at 18:04
  • 1
    The existing answer addresses the confusion from `.push_str()`, but you *could* just implement this function via `self + " bar"`: [playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=019f53a85fd07dd6f5772be1ee30c7da). – kmdreko Dec 28 '22 at 04:00

1 Answers1

2

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.

Rubens Brandão
  • 371
  • 1
  • 5
  • I think this is a correct answer, but might be helpful to add a brief explanation to address OP's misunderstanding? (e.g. Show that the signature of `push_str()` doesn't return anything, so need to explicitly return `self`) – effect Dec 27 '22 at 18:32