型指定をしていないと所有権が移動したものとみなされます
Rust
1fn main(){
2 let mut a=0;
3 let b=&mut a;
4
5 {
6 let c:&mut i32=b; //型指定あり
7 }
8
9 *b+=1;
10 println!("{}",b);
11}
Rust
1fn main(){
2 let mut a=0;
3 let b=&mut a;
4
5 {
6 let c=b; //型指定なし
7 }
8
9 *b+=1;
10 println!("{}",b);
11}
Console
1warning: unused variable: `c`
2 --> Main.rs:6:5
3 |
46 | let c=b;
5 | ^ help: if this is intentional, prefix it with an underscore: `_c`
6 |
7 = note: `#[warn(unused_variables)]` on by default
8
9error[E0382]: borrow of moved value: `b`
10 --> Main.rs:7:15
11 |
125 | let b=&mut a;
13 | - move occurs because `b` has type `&mut i32`, which does not implement the `Copy` trait
146 | let c=b;
15 | - value moved here
167 | println!("{}",*b);
17 | ^^ value borrowed here after move
18 |
19 = note: this error originates in the macro `$crate::format_args_nl` (in Nightly builds, run with -Z macro-backtrace for more info)
20
21error: aborting due to previous error; 1 warning emitted
22
23For more information about this error, try `rustc --explain E0382`.
24
関数の場合は必ず型宣言されるのでエラーにならないという理屈になりますね
型指定の有無で動作に差異が生じる理由は分かりません
詳しい方の解説に期待しましょう...
なお、
この宣言を型宣言ありの形式で表すと
Rust
1let z:&mut i32=&mut *y;
となります
Rust
1let y:&mut i32=& mut x;
に相当するので通常の借用宣言と相違ないことが分かりますね
こちらも参考になるかもしれません
https://colorfulcompany.com/rust/borrow-reference
この質問を見て、以前にも検索結果に似たような内容があったのを思い出して調べたところ、ベストな質問がありました
こちらも参照の価値があるでしょう
https://teratail.com/questions/260892
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2023/11/02 12:28