型推論
The type inference engine is pretty smart. It does more than looking at the type of the value expression during an initialization. It also looks at how the variable is used afterwards to infer its type. Here's an advanced example of type inference:
fn main() { // アノテーションのおかげで、コンパイラは`elem`がu8型であることがわかります。 let elem = 5u8; // 空のベクタ(可変長の配列)を生成。 let mut vec = Vec::new(); // この時点でコンパイラは`vec`の型を知りませんが、 // 何らかの値のベクタ(`Vec<_>`)であるということだけは把握しています。 // `elem`をベクタに挿入。 vec.push(elem); // よし!これでコンパイラは`vec`が`u8`のベクタ(`Vec<u8>`) // であることを把握しました。 // TODO ^ 上の`vec.push(elem)`をコメントアウトしてみましょう。 println!("{:?}", vec); }
このように、変数の型アノテーションは必要ありません。これでコンパイラもプログラマもハッピーですね!