Skip to content

Suggest returning an owned type instead of a reference in E0106 #76007

@scottmcm

Description

@scottmcm

Lifetime elision doesn't allow the following:

fn fizzbuzz() -> &str {
    todo!()
}

The current message has a great hint, but only suggests -> &'static str.

It would be nice if it could also suggest -> String, which would be the better choice for this example.

So maybe it would result in an error something like the following:

error[E0106]: missing lifetime specifier
 --> src/lib.rs:1:18
  |
1 | fn fizzbuzz() -> &str {
  |                  ^ expected named lifetime parameter
  |
  = help: this function's return type contains a borrowed value, but there is no value for it to be borrowed from
help: consider returning an owned value instead
  |
1 | fn fizzbuzz() -> String {
  |                  ^^^^^^
help: or, if this only returns literals or globals, using the `'static` lifetime
  |
1 | fn fizzbuzz() -> &'static str {
  |                  ^^^^^^^^

(Ideally the error can get the corresponding owned type through ToOwned, but just having individual message for &impl Sized and &[T] and &[str] would cover pretty much everything here.)

This idea inspired by the conversation in https://users.rust-lang.org/t/why-not-automatic-inference-of-static-in-foo-str/47913?u=scottmcm

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-suggestion-diagnosticsArea: Suggestions generated by the compiler applied by `cargo fix`C-enhancementCategory: An issue proposing an enhancement or a PR with one.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions