やってみる

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

Rustのデータ型(タプル)

 タプルは異なる型を複数もてる複合型。

成果物

コード

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のフォーマットを{}でなく{:?}とすると表示できる。

参考

対象環境

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

前回まで