size of rust closure

principle

https://doc.rust-lang.org/reference/types/closure.html?highlight=fnonce#closure-types

demo

1

fn f<F : FnOnce() -> String> (g: F) {
    println!("{}", std::mem::size_of::<F>());
    println!("{}", g());
}


fn main() {
    // an immutable string slice(&str)
    let s = "foo";

    f(|| {
        s.to_string()
    });
}

The output will be:

8
foo

2

fn f<F : FnOnce() -> String> (g: F) {
    println!("{}", std::mem::size_of::<F>());
    println!("{}", g());
}


fn main() {
    // type String
    let s = "foo".to_string();

    f(|| {
        s
    });
}

The output will be:

24
foo

posted on 2024-08-18 04:13  winter-loo  阅读(3)  评论(0编辑  收藏  举报

导航