Description
The following code:
fn main() {
let a = String::missing_method();
let b: &str = &a;
let c: String = a;
}
prints the following error messages:
error[E0599]: no function or associated item named `missing_method` found for struct `std::string::String` in the current scope
--> src/main.rs:2:21
|
2 | let a = String::missing_method();
| ^^^^^^^^^^^^^^ function or associated item not found in `std::string::String`
error[E0308]: mismatched types
--> src/main.rs:4:21
|
4 | let c: String = a;
| ------ ^
| | |
| | expected struct `std::string::String`, found `str`
| | help: try using a conversion method: `a.to_string()`
| expected due to this
error: aborting due to 2 previous errors
The compiler appears to have inferred the type of a
to be str
, based on the statement let b: &str = &a
. However, this is almost certainly the wrong thing to do. The fact that an error occurred while type-checking the initial declaration means that we cannot be sure of what type the user intended to use. In this case, unifying &str
with &a
produces an incorrect type of a
, since a deref coercion will likely be involved in the corrected code (e.g. if the user writes let a = String::new()
).
We should be more cautious about inferring the types of locals when an error has occurred. If we are certain that no coercions can be occurring (e.g. passing a
to a function that takes a String
parameter), then continuing on to infer the variable's type should be fine.