rustc suggests calling to_string() on &&str but this generates inefficient code. · Issue #128690 · rust-lang/rust (original) (raw)

If I write some code like:

fn stringify(s: &&str) -> String {
    s
}

then rustc will say something like:

1 | fn stringify(s: &&str) -> String {
  |                           ------ expected `String` because of return type
2 |     s
  |     ^- help: try using a conversion method: `.to_string()`
  |     |
  |     expected `String`, found `&&str`

(see: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=c01bf377e97a0b1c90bd374ba90663a6)

But ToString::to_string() for &&str uses the default implementation which goes via fmt.

Even with optimization this is far less efficient than dereferencing the value first (eg: https://godbolt.org/z/rEoo1qv6x)

Ideally we'd have some better combination of an efficient to_string() override and better advice in error messages.