@@ -39,34 +39,30 @@ consider this code:
39
39
<span class =" filename " >Filename: src/main.rs</span >
40
40
41
41
``` rust
42
- fn do_something () {}
43
-
44
42
fn main () {
45
- for i in 0 .. 100 {
46
- do_something ();
47
- }
43
+ let mut x = 42 ;
44
+ println! (" {x}" );
48
45
}
49
46
```
50
47
51
- Here, we’re calling the ` do_something ` function 100 times , but we never use the
52
- variable ` i ` in the body of the ` for ` loop. Rust warns us about that:
48
+ Here, we’re defining variable ` x ` as mutable , but we never actually mutate it.
49
+ Rust warns us about that:
53
50
54
51
``` console
55
52
$ cargo build
56
53
Compiling myprogram v0.1.0 (file:///projects/myprogram)
57
- warning: unused variable: `i`
58
- --> src/main.rs:4 :9
54
+ warning: variable does not need to be mutable
55
+ --> src/main.rs:2 :9
59
56
|
60
- 4 | for i in 0..100 {
61
- | ^ help: consider using `_i` instead
57
+ 2 | let mut x = 0;
58
+ | ----^
59
+ | |
60
+ | help: remove this `mut`
62
61
|
63
- = note: #[warn(unused_variables)] on by default
64
-
65
- Finished dev [unoptimized + debuginfo] target(s) in 0.50s
62
+ = note: `#[warn(unused_mut)]` on by default
66
63
```
67
64
68
- The warning suggests that we use ` _i ` as a name instead: the underscore
69
- indicates that we intend for this variable to be unused. We can automatically
65
+ The warning suggests that we remove the ` mut ` keyword. We can automatically
70
66
apply that suggestion using the ` rustfix ` tool by running the command `cargo
71
67
fix`:
72
68
@@ -83,16 +79,13 @@ code:
83
79
<span class =" filename " >Filename: src/main.rs</span >
84
80
85
81
``` rust
86
- fn do_something () {}
87
-
88
82
fn main () {
89
- for _i in 0 .. 100 {
90
- do_something ();
91
- }
83
+ let x = 42 ;
84
+ println! (" {x}" );
92
85
}
93
86
```
94
87
95
- The ` for ` loop variable is now named ` _i ` , and the warning no longer appears.
88
+ The ` x ` variable is now immutable , and the warning no longer appears.
96
89
97
90
You can also use the ` cargo fix ` command to transition your code between
98
91
different Rust editions. Editions are covered in [ Appendix E] [ editions ] .
0 commit comments