やってみる

アウトプットすべく己を導くためのブログ。その試行錯誤すらたれ流す。

Rustのデータ型(配列)

 固定長。

成果物

コード

fn main() {
    let a = [1, 3, 5];
    println!("{:?}", a);

    println!("{}", a[0]);
    println!("{}", a[1]);
    println!("{}", a[2]);

    let mut a = [0, 2, 4];
    println!("{:?}", a);
    a[2] = 444;
    println!("{}", a[2]);
}

実行

$ rustc main.rs
$ ./main
[1, 3, 5]
1
3
5
[0, 2, 4]
444

エラー

インデックス範囲外

fn main() {
    let a = [1, 3, 5];
    println!("{}", a[3]);
}
error: index out of bounds: the len is 3 but the index is 3
  --> main.rs:12:20
   |
12 |     println!("{}", a[3]);
   |                    ^^^^
   |
   = note: #[deny(const_err)] on by default

error: aborting due to previous error

再代入できない

fn main() {
    let a = [1, 3, 5];
    a[2] = 55;
    println!("{}", a[2]);
}
error[E0594]: cannot assign to indexed content `a[..]` of immutable binding
  --> main.rs:14:5
   |
6  |     let a = [1, 3, 5];
   |         - help: make this binding mutable: `mut a`
...
14 |     a[2] = 55;
   |     ^^^^^^^^^ cannot mutably borrow field of immutable binding

error: aborting due to previous error

For more information about this error, try `rustc --explain E0594`.

 イミュータブルだと要素も再代入できない。ミュータブルにすれば解決。(エラーが親切に教えてくれる)

対象環境

$ uname -a
Linux raspberrypi 4.19.42-v7+ #1219 SMP Tue May 14 21:20:58 BST 2019 armv7l GNU/Linux

前回まで