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
*/
fn main() {
    enum SpreadsheetCell {
        Int(i32),
        Float(f64),
        Text(String),
    }
    
    let row = vec![
        SpreadsheetCell::Int(3),
        SpreadsheetCell::Text(String::from("blue")),
        SpreadsheetCell::Float(10.12),
    ];

    for r in &row {
        match r {
            SpreadsheetCell::Int(i) => println!("{}", i),
            SpreadsheetCell::Text(s) => println!("{}", s),
            SpreadsheetCell::Float(f) => println!("{}", f),
        }
    }
}
3
blue
10.12

https://doc.rust-jp.rs/book-ja/ch08-01-vectors.html#enumを使って複数の型を保持する

ベクタの要素を不変変数借用した場合は、そのベクタの要素を変更・追加できなくなる

let mut v = vec![1, 2, 3, 4, 5];
let first = &v[0];
v.push(6);
println!("The first element is: {}", first);
/*
error[E0502]: cannot borrow `v` as mutable because it is also borrowed as immutable
  --> src\main.rs:23:5
   |
21 |     let first = &v[0];
   |                  - immutable borrow occurs here
22 | 
23 |     v.push(6);
   |     ^^^^^^^^^ mutable borrow occurs here
24 | 
25 |     println!("The first element is: {}", first);
   |                                          ----- immutable borrow later used here
*/

ベクタの解放

2022/2/18 21:38:00

ベクタがスコープを抜けると自動で解放される。

ベクタの範囲外の要素を取得しようとした場合、[]ではプログラムが停止するが、getではNoneが返されプログラムが停止しない。

ベクタの変更

2022/2/18 21:38:00

値の変更や追加には、変数宣言時にmutをつける必要がある。

let mut v = Vec::new();
v.push(5);
v.push(6);
v.push(7);
v.push(8);

ベクタの作成

2022/2/18 21:37:00
let v1: Vec<i32> = Vec::new();
let v2 = vec![1, 2, 3];
println!("v1:{}", v2[2]);    //3