gpt4 book ai didi

rust - Rust 中的函数是一等对象吗?

转载 作者:行者123 更新时间:2023-11-29 07:42:25 25 4
gpt4 key购买 nike

函数可以作为参数传递吗?例如,在 JavaScript 中,您可以像这样将函数作为参数传递:

setInterval(function() { /*...*/ }, 1000);

最佳答案

他们是一流的。与 JavaScript 相比,Rust 有两种类型 - 函数和闭包。

fn first_class() {
println!("function");
}

fn higher_kinded<F: FnOnce()>(cb: F) {
cb();
}

fn main() {
higher_kinded(first_class); // passing function
higher_kinded(|| println!("closure")); // passing closure
}

关于rust - Rust 中的函数是一等对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24972394/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com