Rustを学びます
勉強ページは日本語ドキュメント参考
プログラミング言語Rust
Rustの日本語ドキュメント 2nd Edition
https://doc.rust-jp.rs/book/second-edition/
オリジナル
https://doc.rust-lang.org/book/
3. Common Programming Concepts
3.5 フロー制御
if!!
fn main(){
let number = 3;
if number < 5 {
println!("condition was true");
}else{
println!("condition was false");
}
}
条件式はboolのみです。0とか1を代用できません。
“`rust
fn main(){
let number = 1;
if number {
println!("condition was true");
}else{
println!("condition was false");
}
}
===
error[E0308]: mismatched types
–> src/main.rs:5:8
|
5 | if number {
| ^^^^^^ expected bool, found integer
|
= note: expected type bool
found type {integer}
error: aborting due to previous error
let文内でif式を使う
```rust
fn main(){
let condition = true;
let number = if condition{
5
}else{
6
};
println!("number is {}", number);
}
loop!!
fn main(){
let mut count: i32 = 0;
loop{
println!("loop {}", count);
if count >= 1_000 {
break;
}
count += 1;
}
}
whileでfor
fn main(){
let a = [10, 20, 30, 40, 50];
let mut index = 0;
while index < 5 {
println!("value is {}", a[index]);
index = index + 1;
}
}
for
fn main(){
let a = [10, 20, 30, 40, 50];
for elem in a.iter(){
println!("value is {}", elem);
}
}
range関数(start..end)
fn main(){
for number in (1..4) {
println!("number is {}", number);
}
for number in (1..4).rev() {
println!("number is {}", number);
}
}
==
number is 1
number is 2
number is 3
// rev
number is 3
number is 2
number is 1
イエス!