20. ビルドには(makeではなく)cargoを使う
% pwd
/tmp/hello
% mkdir src
% mv hello.rs src/main.rs
% cargo init
Created library project
% cargo run
Compiling hello v0.1.0 (file:///tmp/hello)
Finished dev [unoptimized + debuginfo] target(s) in 0.xx secs
Running `target/debug/hello`
hello, world.
%
シンプルなCargo.tomlを生成。
必要に応じて手直しする。
コマンド 意味
cargo run コンパイルして即実行
cargo build ビルドのみ
cargo test テストコードを実行
cargo doc ドキュメントを生成
cargo clean target/を削除
20
21. 簡単な紹介
ファンクションはfnで定義する。(hello.rsでみたとおり)
別のソースから参照されるものはpub fnと書く。
変数や値の型はu8, u16, u32, i8, i16, i32など。後ろに書く。
fn testfunc(arg: u32) -> u32 {
let a: u32 = 1;
let b = a + 1;
let a = b + arg;
let mut c = a + b;
c = c * 2;
a + b + c
}
Cでいうところの
uint32_t testfunc(uint32_t arg)
型宣言して初期値を代入、変更不可能
右辺の型がわかるので省略(型推論)
新しいaを宣言(以前のaは参照できない)
cはmutable(変更できる)
最後に式を書くとリターン値になる
Cのようにreturn a + b + c;
と書いてもよい
21
23. 型キャスト
式 as 型 でキャストできる。
符号なし整数でもサイズが違うと別の型。
違う型の値どうしの演算をする場合キャストが必要。
let shortval: u16 = 3;
let longval: u32 = 5;
let ans = shortval + longval;
shortval as u32 + longval 型が違うのでこの記述は
エラーになりビルドできない
キャストして
型を合わせて演算する
23
24. 条件分岐
if a == b {
println!(”equal”);
} else {
println!(”a == {} but b == {}”, a, b);
}
match a {
1 => println!(”one”),
2 => println!(”two”),
_ => println!(”other”),
}
Cのswitch caseでの
defaultに相当
24
25. ループ
forはあるが、Cとだいぶ異なる記法。 (Python等に似ている)
let values: [u32; 5] = [ 3, 5, 7, 9, 11];
for value in values.iter() {
…
}
for i in 0..10 { … } // 0~9 (10ではない)
whileはCなどと同様。
while !done { // done != trueと同じ
…
}
loop { … } は while true { … } と同じ。永久ループ。
break; や continue; はCと同様。ラベルを付けてそこに飛ぶことも可能。
’label1: while !done {
loop {
if a == b { continue ’label1; }
}
}
25