LoginSignup
3
1

More than 5 years have passed since last update.

if let さっぱり分からん☆(^~^)

Last updated at Posted at 2019-03-24

cargo clippy とかしてるとお前の match 構文よりもっと良い if let というもっと簡潔な書き方がある、とオヌヌメが入ってくる。

if let

rust は ヌル なんか使わない言語なんで

let mut fruit: Option<String>;
fruit = Some("Applet".to_string());
fruit = None;
fruit = Some("Banana".to_string());
fruit = Some("Casava".to_string());

Option にくるんで Some か None で分ける。
Some なら中身は有るし、 None なら中身は無い。

そこで中身を使うために

let mut fruit;
match fruit_box {
    Some(content) =>{
        fruit = content
    },
    None => {},
};

といった match 構文を使ったときに Oh,my god! といった感情が表される☆
この書き方はヘタクソなのか。フーム☆(^~^)

りくつでいうと、以下のように書けばいいらしい。

if let Some(content) = fruit_box {
    fruit = content
};

うーむ☆(^~^)
Some(content) と None しかないのだから、 match にするまでもないから if なのか☆

if文の条件式のところに == ではなく = があるので 違和感 があるが、
if 文は 条件分岐 で、
if-let 文は Some の中身を取り出すだけで 別物だな☆(^~^)

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