1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

競プロのためのRust入門#4 条件分岐(if文)

1
Posted at

4.0はじめに

前回の記事では演算について学びました。
今回は条件分岐(if文)です。

4.1 if文の基本

まずはif文を使ったコードを見てみましょう。

fn main(){
  let a = 10;
  if a > 5{
    println!("aは5よりも大きい");
  }
}

実行結果

aは5よりも大きい

基本的な書き方は

if 条件式 {
    //条件が成立したときに行う処理
}

条件式がtrueのときは{}内の処理が行われます。
falseのときは行われません。

4.2 else

if文だけでは条件式がtrueになったときしか処理が行われません。
ここで、elseをつかうことで条件式がfalseになったときでも処理を行えます。
次のコードはaが2で割り切れるときは偶数を、割り切れないときは奇数を出力するコードです。

fn main(){
  let a = 7;
  if a % 2 == 0{
    println!("偶数");
  }else{
    println!("奇数");
  } 
}

実行結果

奇数

4.3 else if

3通り以上に分岐させるためには基本的にelse ifを使います。
上から順番に判定されます。

fn main(){
  let score = 7;
  if score<=5{
    println!("5以下");
  }else if score<=7{
    println!("6か7");
  }else{
    println!("8以上");
  }
}

実行結果

6か7

4.4 Rust特有のif式の使い方

fn main(){
  let a = 10;
  let result = if a%2 == 0 {
    "偶数"
  }else{
    "奇数"
  };
  println!("{}",result);
}

実行結果

偶数

なんとif文は単に条件分岐だけでなく、値を返す式として使えます。

4.5 よくある間違い、気を付けるポイント

このようなif文の使い方はコンパイルエラーになります。

fn main(){
    if true{
      10
    }
    else{
      "Rust"
    };
}

Rustではif文の各分岐で返される値の型を一致させる必要があるからです。(ただし、if側とelse側で異なる型のものを使用してはならないという事ではありません)
一方、

fn main(){
    if true{
      10
    }
    else{
      20
    };
}

このコードは正しく動きます。
なぜなら、両方の分岐が整数値を返すからです。


ifの条件式はbool型にする必要があります。
次のようなコードはCEになります。

fn main(){
  let a = 10;
  if a {
    println!("{}",a);
  }
}

一方、

fn main(){
  let a = 10;
  if a>0 {
    println!("{}",a);
  }
}

とすると、a>0はbool型になるので正しく動作します。

参考資料

1
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?