LoginSignup
1
0

More than 1 year has passed since last update.

制御構文

Posted at

if

条件分岐の結果をそのまま代入できる。

fn main() {
    let a = 10;
    let b = if a > 5 {
        println!("a > 5");
        a + 10
    } else {
        println!("a <= 5");
        a - 10
    };
    println!("{}", b);
}

繰り返し

Loop

breakした値が戻り値になる。

fn main() {
    let mut i = 0;
    let result = loop {
        println!("count: {}", i);
        if i == 10 {
            break i * 2;
        }
        i += 1;
    };
    println!("{}", result);
}

While

fn main() {
    let mut i = 0;

    while i < 10 {
        println!("count: {}", i);
        i += 1;
    }
    println!("{}", i);
}

for

fn main() {
    // 繰り返し回数が決まっている場合
    for i in 0..10 {
        println!("{}", i);
    }

    // 繰り返す要素が決まっている場合
    let array: [i32; 10] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    for i in array {
        println!("{}", i);
    }
}

range型

for i in 1..101..10のような書き方はRange型が返る。

fn main() {
    let a = 1..10;
    println!("{:?}", a);
}

Iterator

繰り返し処理が適用できるのはIteratorトレイとが実装されているため。

自作した型にもIteratorトレイトを適用すればforループで繰り返し処理ができる。

// 自作の型を定義
struct Iter {
    current: usize,
    max: usize,
}

// 繰り返しょ処理の内容を定義
impl Iterator for Iter {
    type Item = usize; // 出力する型を紐付け

    // 次の要素に進む場合の処理next()を実装
    fn next(&mut self) -> Option<usize> {
        self.current += 1;
        if self.current < self.max {
            Some(self.current)
        } else {
            None
        }
    }
}

fn main() {
    let it = Iter {
        current: 0,
        max: 10,
    };
    for num in it {
        println!("{}", num);
    }
}

パターンマッチング

値を見る場合

fn main() {
    let i = 1;
    match i {
        1 => println!("one"),
        2 => println!("two"),
        _ => println!("other"),
    }
}

型を見る場合

enumを使う場合はenumの要素を網羅する必要がある

// 型の場合
fn main() {
    enum Color {
        Red,
        Blue,
        Green,
    }
    let c = Color::Red;
    let _1 = Color::Blue;
    let _2 = Color::Green;
    match c {
        Color::Red => println!("red"),
        Color::Blue => println!("blue"),
        // Color::Green => println!("green"), // Greenをコメントアウト
        // _ => println!("other"), // otherもコメントアウト
    }
}

結果↓

error[E0004]: non-exhaustive patterns: `Green` not covered
  --> src/main.rs:15:11
   |
7  | /     enum Color {
8  | |         Red,
9  | |         Blue,
10 | |         Green,
   | |         ----- not covered
11 | |     }
   | |_____- `Color` defined here
...
15 |       match c {
   |             ^ pattern `Green` not covered
   |
   = help: ensure that all possible cases are being handled, possibly by adding wildcards or more match arms
   = note: the matched value is of type `Color`
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0