タプルは異なる型の値の集合。括弧を用いて生成する。
fn main(){
let tup = (10, "20", 30);
println!("{}, {}, {}", tup.0, tup.1, tup.2);
}
C++でタプルを使用する場合は、型を指定しなければいけないが、Rustの場合は型指定がない。つまり自動で型推論をやってくれている?
#include <iostream>
#include <string>
#include <tuple>
#include <vector>
int main()
{
std::tuple<int, double, std::string> t1{100, 1.1, "aaa"};
std::tuple<std::string, int, int> t2{"bbb", 200, 300};
std::vector<std::tuple<std::string, int, int>> v =
{
{"ccc", 400, 500},
{"ddd", 600, 700}
};
}
Rustではインデックスを用いて値にアクセスできるが、以下のような書き方をするとエラーとなる。
fn main(){
let tup = (1, 1.2, "tupple");
for n in 0..2 {
println!("{}", tup.n);
}
}
$ rustc main.rs
error[E0609]: no field `n` on type `({integer}, {float}, &str)`
–> main.rs:4:28
|
4 | println!(“{}”, tup.n);
| ^ unknown field
error: aborting due to 1 previous error
For more information about this error, try `rustc –explain E0609`.
また、型推論できない場合は、型を明示する必要がある。