Only suggest removal of as_* and to_ conversion methods on E0308

Instead of

```
error[E0308]: mismatched types
 --> tests/ui/suggestions/only-suggest-removal-of-conversion-method-calls.rs:9:5
  |
4 | fn get_name() -> String {
  |                  ------ expected `String` because of return type
...
9 |     your_name.trim() //~ ERROR E0308
  |     ^^^^^^^^^^^^^^^^ expected `String`, found `&str`
  |
help: try removing the method call
  |
9 -     your_name.trim()
9 +     your_name
```

output

```
error[E0308]: mismatched types
  --> $DIR/only-suggest-removal-of-conversion-method-calls.rs:9:5
   |
LL | fn get_name() -> String {
   |                  ------ expected `String` because of return type
...
LL |     your_name.trim()
   |     ^^^^^^^^^^^^^^^^- help: try using a conversion method: `.to_string()`
   |     |
   |     expected `String`, found `&str`
```

Fix #114329.
This commit is contained in:
Esteban Küber 2024-01-29 19:07:36 +00:00
parent fb4bca04fa
commit 44d8ecbfb8
4 changed files with 48 additions and 0 deletions

View File

@ -261,6 +261,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
expr.kind
&& let Some(recv_ty) = self.typeck_results.borrow().expr_ty_opt(recv_expr)
&& self.can_coerce(recv_ty, expected)
&& let name = method.name.as_str()
&& (name.starts_with("to_") || name.starts_with("as_") || name == "into")
{
let span = if let Some(recv_span) = recv_expr.span.find_ancestor_inside(expr.span) {
expr.span.with_lo(recv_span.hi())

View File

@ -0,0 +1,16 @@
// run-rustfix
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().to_string() //~ ERROR E0308
}
fn main() {
println!("Hello, What is your name? ");
let your_name = get_name();
println!("Hello, {}", your_name)
}

View File

@ -0,0 +1,16 @@
// run-rustfix
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() //~ ERROR E0308
}
fn main() {
println!("Hello, What is your name? ");
let your_name = get_name();
println!("Hello, {}", your_name)
}

View File

@ -0,0 +1,14 @@
error[E0308]: mismatched types
--> $DIR/only-suggest-removal-of-conversion-method-calls.rs:9:5
|
LL | fn get_name() -> String {
| ------ expected `String` because of return type
...
LL | your_name.trim()
| ^^^^^^^^^^^^^^^^- help: try using a conversion method: `.to_string()`
| |
| expected `String`, found `&str`
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0308`.