Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add explanation for
&mut self
method call when expecting -> Self
When a user tries to use a method as if it returned a new value of the same type as its receiver, we will emit a type error. Try to detect this and provide extra explanation that the method modifies the receiver in-place. This has confused people in the wild, like in https://users.rust-lang.org/t/newbie-why-the-commented-line-stops-the-snippet-from-compiling/47322
- Loading branch information
Showing
4 changed files
with
70 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
4 changes: 4 additions & 0 deletions
4
src/test/ui/suggestions/chain-method-call-mutation-in-place.rs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
fn main() {} | ||
fn foo(mut s: String) -> String { | ||
s.push_str("asdf") //~ ERROR mismatched types | ||
} |
20 changes: 20 additions & 0 deletions
20
src/test/ui/suggestions/chain-method-call-mutation-in-place.stderr
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
error[E0308]: mismatched types | ||
--> $DIR/chain-method-call-mutation-in-place.rs:3:5 | ||
| | ||
LL | fn foo(mut s: String) -> String { | ||
| ------ expected `std::string::String` because of return type | ||
LL | s.push_str("asdf") | ||
| ^^^^^^^^^^^^^^^^^^ expected struct `std::string::String`, found `()` | ||
| | ||
note: method `push_str` modifies its receiver in-place | ||
--> $DIR/chain-method-call-mutation-in-place.rs:3:7 | ||
| | ||
LL | s.push_str("asdf") | ||
| - ^^^^^^^^ this call modifies `s` in-place | ||
| | | ||
| you probably want to use this value after calling the method... | ||
= note: ...instead of the `()` output of method `push_str` | ||
|
||
error: aborting due to previous error | ||
|
||
For more information about this error, try `rustc --explain E0308`. |