|
ToDo:
|
これコンパイルエラーです。
fn main() {
let mut x = 5;
let y = &mut x;
*y = 1;
println!("{}",y);
println!("{}",x);
}
yがxを借用しているのだがそのyの生存期間がxより早く終わらない
error[E0502]: cannot borrow `x` as immutable because it is also borrowed as mutable
--> src/main.rs:8:19
|
4 | let y = &mut x;
| - mutable borrow occurs here
...
8 | println!("{}",x);
| ^ immutable borrow occurs here
9 | }
| - mutable borrow ends here
error: aborting due to previous error
だから{}でyの生存期間を短くしてやると通る
fn main() {
let mut x = 5;
{
let y = &mut x;
*y = 1;
println!("{}",y);
}
println!("{}",x);
}
あと*yで参照の実体*1を変更しているので出力は
1
1
です。
*1 表現あってる?
これは通る
fn main() {
let spaces = " ";
let spaces = spaces.len();
println!("{}",spaces);
}
がこれは警告で通る
fn main() {
let mut spaces = " ";
let spaces = spaces.len();
println!("{}",spaces);
}
Compileメッセージ
warning: variable does not need to be mutable
--> src/main.rs:2:9
|
2 | let mut spaces = " ";
| ^^^^^^^^^^
|
= note: #[warn(unused_mut)] on by default
Finished dev [unoptimized + debuginfo] target(s) in 0.32 secs
Running `target/debug/study`
1