Closed
Description
Summary
When you have a function that returns a String but add .trim()
to the return value to remove extraneous whitespace, you have a type error because .trim()
returns a &str
. But the suggestion is not to add .to_owned()
or to_string()
to fix the problem but to remove the trimming behavior entirely even if that is exactly what the programmer intended.
When using cargo run, it additionally fails to show the line containing .trim() in the suggested change.
Lint Name
error[E0308]: mismatched types
Reproducer
I tried this code:
use std::io::stdin;
fn get_name() -> String {
let mut your_name = String::new();
stdin()
.read_line(&mut your_name)
.expect("Failed to read the line for some reason");
your_name
.trim()
}
fn main() {
println!("Hello, What is your name? ");
let your_name = get_name();
println!("Hello, {}", your_name)
}
I saw this happen:
Checking treehouse v0.1.0 (C:\Users\OpenM\Code\Projects\Rust\treehouse)
error[E0308]: mismatched types
--> src\main.rs:8:2
|
3 | fn get_name() -> String {
| ------ expected `std::string::String` because of return type
...
8 | / your_name
9 | | .trim()
| |_______________^ expected `String`, found `&str`
|
help: try removing the method call
|
8 - your_name
9 - .trim()
8 + your_name
|
For more information about this error, try `rustc --explain E0308`.
error: could not compile `treehouse` (bin "treehouse") due to previous error
I expected to see this happen:
Checking treehouse v0.1.0 (C:\Users\OpenM\Code\Projects\Rust\treehouse)
error[E0308]: mismatched types
--> src\main.rs:8:2
|
3 | fn get_name() -> String {
| ------ expected `std::string::String` because of return type
...
8 | / your_name
9 | | .trim()
| |_______________^ expected `String`, found `&str`
|
help: add .to_owned() to return a String instead of a &str
|
8 - your_name
9 - .trim()
8 + your_name
9 + .trim().to_owned()
|
For more information about this error, try `rustc --explain E0308`.
error: could not compile `treehouse` (bin "treehouse") due to previous error
Version
rustc 1.68.0 (2c8cc3432 2023-03-06)
binary: rustc
commit-hash: 2c8cc343237b8f7d5a3c3703e3a87f2eb2c54a74
commit-date: 2023-03-06
host: x86_64-pc-windows-msvc
release: 1.68.0
LLVM version: 15.0.6
Additional Labels
No response