Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

closureを使う関数を自作で作る #2

Open
nobu513 opened this issue Oct 26, 2022 · 1 comment
Open

closureを使う関数を自作で作る #2

nobu513 opened this issue Oct 26, 2022 · 1 comment

Comments

@nobu513
Copy link
Owner

nobu513 commented Oct 26, 2022

最近closureを見にする機会が増えた。中身がどうやって実装されているのかイメージしたいので、簡単に自作でclosureを使わせる関数を実装してみる。

ref

まずはclosureがそもそも何なのか調べる。

疑問点

  • closureとmoveを一緒に使うやつ。
@nobu513
Copy link
Owner Author

nobu513 commented Oct 26, 2022

[ask]
closureにmutがついているのがちょっと不思議に感じる。

fn main() {
    let mut count = 0;
    let mut inc = || {
        count += 1;
        println!("{}", count);
    };
    inc();
    println!("{}", count);
}

どうやら、closureはFn, FnOnce, FnMutというトレイトを自動で実装するらしい。それらの中身はまだしらんけど、おそらく変数をキャプチャするかどうかでclosureにmutをつけるかどうかが決定されるんだろう。(ref: https://stackoverflow.com/questions/49986734/when-should-i-add-mut-to-closures)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant