0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

matchesマクロの紹介(rust)

Last updated at Posted at 2023-02-11

matchesの紹介をします。

rustのパターンマッチを使えば、以下のような書き方ができます。

let maybe_name = Some("にわか");
if let Some(_) = maybe_name {
    println!("名前があった。");
}

パターンにマッチするかどうかだけ興味があるのに、こういう書き方をするのは冗長な気がします。

matchesを使えば、もっとシンプルにできます。

let maybe_name = Some("にわか");
if matches!(maybe_name, Some(_)) {
    println!("名前があった。");
}

シンプルにかけました。matchestrueもしくはfalseを返します。

テストコードで確認してみましょう。

#[test]
fn test_matches() {
    let mut maybe_name = Some("にわか");
    assert_eq!(matches!(maybe_name, Some(_)), true);
    maybe_name = None;
    assert_eq!(matches!(maybe_name, None), true);
}

終わり。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?