Skip to content

Compiler suggestion "try using a conversion method: .to_string" #105494

Closed
@Deleplace

Description

@Deleplace

I tried this code (playground):

fn main() {
    let mut path: String = "/usr".to_string();
    let folder: String = "lib".to_string();
    
    path = format!("{}/{}", path, folder).as_str();
    
    println!("{}", &path);
}

I expected to see this happen:

error[[E0308]](https://doc.rust-lang.org/stable/error-index.html#E0308): mismatched types
 --> src/main.rs:6:12
  |
2 |     let mut path: String = "/usr".to_string();
  |                   ------ expected due to this type
...
5 |     path = format!("{}/{}", path, folder).as_str();
  |            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^- help: try removing the call to method: `.as_str()`
  |            |
  |            expected struct `String`, found `&str`

Instead, this happened:

error[[E0308]](https://doc.rust-lang.org/stable/error-index.html#E0308): mismatched types
 --> src/main.rs:6:12
  |
2 |     let mut path: String = "/usr".to_string();
  |                   ------ expected due to this type
...
5 |     path = format!("{}/{}", path, folder).as_str();
  |            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^- help: try using a conversion method: `.to_string()`
  |            |
  |            expected struct `String`, found `&str`

This is just a very specific instance where the suggestion to add some code, while "technically correct", is less useful than the better suggestion to remove some code.

Meta

rustc --version --verbose:

rustc 1.65.0 (897e37553 2022-11-02)
binary: rustc
commit-hash: 897e37553bba8b42751c67658967889d11ecd120
commit-date: 2022-11-02
host: aarch64-apple-darwin
release: 1.65.0
LLVM version: 15.0.0
Backtrace

<backtrace>

Metadata

Metadata

Assignees

Labels

A-diagnosticsArea: Messages for errors, warnings, and lintsA-suggestion-diagnosticsArea: Suggestions generated by the compiler applied by `cargo fix`C-bugCategory: This is a bug.D-papercutDiagnostics: An error or lint that needs small tweaks.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