rust-lang / rust

Empowering everyone to build reliable and efficient software.
https://www.rust-lang.org
Other
93.93k stars 12.09k forks source link

Tracking Issue for `push_str` returning `self` #125264

Closed hamirmahal closed 2 weeks ago

hamirmahal commented 2 weeks ago

Feature gate: #![feature(push_str_returns_self)]

This is a tracking issue for push_str returning self.

Public API

  pub fn push_str(&mut self, string: &str) -> &mut Self {
      self.vec.extend_from_slice(string.as_bytes());
      self
  }

Steps / History

Unresolved Questions

hamirmahal commented 2 weeks ago

Motivation

This change would clean up functions like this.

Without this change

fn foo(mut s: String, domain: &str) -> String {
    s = s.trim().to_string();
    s.push('@');
    s.push_str(domain);
    s
}

With this change

fn foo(mut s: String, domain: &str) -> String {
    s = s.trim().to_string();
    s.push('@');
    s.push_str(domain)
}
hamirmahal commented 2 weeks ago

Drawbacks

If push_str returns self, now, it'll be more difficult to change it to something else, later, like self.len().

Although I will say that returning self.len() is worse than returning self, since it's trivial to get self.len() given self, but not the other way around.

dtolnay commented 2 weeks ago

Normally a tracking issue is not required for "instantly stable" changes i.e. standard library changes which do not require the user to enable a particular #![feature(...)] in order to use. push_str is not behind such a feature gate.