Skip to content

Improve diagnostics when accidentally making str instead of &str #88800

Open
@jruderman

Description

@jruderman

Given the following code:

fn first_three(s: &str) -> String {
    String::from(s[0..3])
}

fn main() {
    println!("{}", first_three("hello"));
}

The current output is:

error[E0277]: the size for values of type `str` cannot be known at compilation time
   --> src/main.rs:2:18
    |
2   |     String::from(s[0..3])
    |                  ^^^^^^^ doesn't have a size known at compile-time
    |
    = help: the trait `Sized` is not implemented for `str`
note: required by `from`

error[E0277]: the trait bound `String: From<str>` is not satisfied
   --> src/main.rs:2:5
    |
2   |     String::from(s[0..3])
    |     ^^^^^^^^^^^^ the trait `From<str>` is not implemented for `String`
    |
    = help: the following implementations were found:
              <String as From<&String>>
              <String as From<&mut str>>
              <String as From<&str>>
              <String as From<Box<str>>>
            and 2 others
note: required by `from`

error[E0277]: the size for values of type `str` cannot be known at compilation time
 --> src/main.rs:2:5
  |
2 |     String::from(s[0..3])
  |     ^^^^^^^^^^^^ doesn't have a size known at compile-time
  |
  = help: the trait `Sized` is not implemented for `str`
  = note: all function arguments must have a statically known size
  = help: unsized fn params are gated as an unstable feature

Ideally the output should look like:

help: borrow as a &str slice: &s[0..3]

(and perhaps a bit less verbosity on the errors; #56607 will help)

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsT-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