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

rust クロージャってなんだ!?

Posted at

数字が入っている配列の最も大きい値のインデックス値が欲しくなった

調べたらこのようなプログラムが、、、

fn main() {
    let arr = [3, 10, 5, 8, 12, 7];

    // 最大値の要素番号(インデックス)を取得
    let max_index = arr.iter()
        .enumerate()
        .max_by_key(|&(_, &value)| value)
        .map(|(index, _)| index);

    match max_index {
        Some(idx) => println!("最大値の要素番号: {}", idx),
        None => println!("配列が空です"),
    }
}

え。。。?

        .max_by_key(|&(_, &value)| value)
        .map(|(index, _)| index);

なにこれ・・・?

と思って調べました

クロージャ(無名関数) で、Rust の max_by_key() に渡される比較用の関数らしいです

まだよくわからない

クロージャとは

|x, y| x + y のように |引数| 処理 という形で書く。

凄くわかりやすい記事

このような例も

fn main() {
    let add = |x, y| x + y; // クロージャ
    println!("{}", add(2, 3)); // 出力: 5
}

このような使い方以外にも、このクロージャ式を関数の引数に書いて、そのクロージャの結果をかんすうにひきすうとして渡すこともできるのだとか。

クロージャのような機能に触れたことがないのでびっくりです

そもそも知らなかったけど、Rust では *_(アンダースコア)には 「無視する(不要な値)」 という意味があります。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?