t_wの輪郭

Feedlyでフォローするボタン

読み込みのみ

let v = vec![100, 32, 57];
for i in &v {
    println!("{}", i);
}
/*
100
32
57
*/

書き込み

let mut v = vec![100, 32, 57];
for i in &mut v {
    *i += 50;
}
for i in &v {
    println!("{}", i);
}
/*
150
82
107
*/

ベクタの値を走査する時にベクタに参照(&)を使う理由は、所有権の移動が発生し、走査して以降ベクタが利用できなくなるからである。

参照を使わずに所有権の移動する例

let v = vec![100, 32, 57];
for i in v {
    println!("{}", i);
}

for i in v {
    println!("{}", i);
}
error[E0382]: use of moved value: `v`
   --> src\main.rs:8:10
    |
3   | let v = vec![100, 32, 57];
    |     - move occurs because `v` has type `Vec<i32>`, which does not implement the `Copy` trait
4   | for i in v {
    |          -
    |          |
    |          `v` moved due to this implicit call to `.into_iter()`
    |          help: consider borrowing to avoid moving into the for loop: `&v`
...
8   | for i in v {
    |          ^ value used here after move
    |