固定長。
成果物
コード
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`.
イミュータブルだと要素も再代入できない。ミュータブルにすれば解決。(エラーが親切に教えてくれる)
対象環境
- Raspbierry pi 3 Model B+
- Raspbian stretch 9.0 2018-11-13
- bash 4.4.12(1)-release
$ uname -a Linux raspberrypi 4.19.42-v7+ #1219 SMP Tue May 14 21:20:58 BST 2019 armv7l GNU/Linux
前回まで
- Rustを学んでみたい(プログラミング言語)
- Rustの環境構築
- RustでHelloWorld
- Rustの和訳ドキュメント
- Cargoでプロジェクト作成・ビルド・実行
- クレートとは?
- Rustで関数を使ってみる
- Rustでモジュールを使ってみる
- Rustで乱数を生成する(rand)
- Rustで標準入力する(std::io::stdin().read_line())
- RustでMatch判定する(match)
- Rustでprintとread_lineを1行にする方法
- Rustで数当てゲーム
- クレート名にドット.が使えない
- Rustの変数と可変性(let, mut) error[E0384]: cannot assign twice to immutable variable
x
- Rustのimmutable束縛とconst定数の違い
- RustのREPL、evcxrのインストールに失敗した
- Rustでコンパイルするときの変数未使用warningを消す
- Rustの変数(再代入、再宣言(シャドーイング))
- Rustのシャドーイングについて
- イミュータブルについて(副作用)
- Rustの定数(const)
- Rustのデータ型(数値)
- Rustのデータ型(論理)
- Rustのデータ型(文字)
- Rustのデータ型(タプル)