タプルは異なる型を複数もてる複合型。
成果物
コード
fn main() { let tuple: (i32, char) = (100, 'A'); println!("tuple {:?}", tuple); // 要素を参照(インデックス) println!("tuple.0 {}", tuple.0); println!("tuple.1 {}", tuple.1); // 分解 let (i1, c1) = tuple; println!("i1 {}", i1); println!("c1 {}", c1); // 要素が1つのときはカンマを付与することで演算子の括弧と区別する println!("tuple litteral {:?}", (200,)); println!("value {:?}", (200)); }
実行
$ rustc main.rs $ ./main
tuple (100, 'A') i1 100 c1 A tuple litteral (200,) value 200 tuple.0 100 tuple.1 A
エラー
タプルをprintln!
error[E0277]: `(i32, char)` doesn't implement `std::fmt::Display` --> main.rs:7:26 | 7 | println!("tuple {}", tuple); | ^^^^^ `(i32, char)` cannot be formatted with the default formatter | = help: the trait `std::fmt::Display` is not implemented for `(i32, char)` = note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead = note: required by `std::fmt::Display::fmt` error: aborting due to previous error For more information about this error, try `rustc --explain E0277`.
plintlnのフォーマットを{}
でなく{:?}
とすると表示できる。
参考
- https://doc.rust-jp.rs/book/second-edition/ch03-02-data-types.html
- https://17-60434459-gh.circle-artifacts.com/0/tmp/circle-artifacts.OLYd1K7/rust-by-example/primitives/tuples.html
対象環境
- 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のデータ型(文字)