是什么使得在 Rust 中需要函数指针类型的地方可以使用闭包类型?
What enables a closure type to be used where a function pointer type is expected in Rust?
是什么使得闭包类型可以用于函数指针类型?
fn takes_ptr(_f: fn(u32) -> u32) {}
fn main() {
let closure = |n| n;
takes_ptr(closure)
}
related: there's another question that asks what enables pointer types to be used where closure types are expected:
如果闭包不捕获任何局部变量,则可以将其强制转换为函数指针。
不捕获任何变量的闭包实际上与普通函数相同,这听起来像是。此行为在 RFC 1558 中定义,它表示:
A closure that does not move, borrow, or otherwise access (capture) local variables should be coercable to a function pointer (fn
).
所以 |n| n
可以被强制转换,因为它不捕获任何局部变量,但是 |n| n + a
不能被转换,因为它从外部环境捕获变量 a
。
是什么使得闭包类型可以用于函数指针类型?
fn takes_ptr(_f: fn(u32) -> u32) {}
fn main() {
let closure = |n| n;
takes_ptr(closure)
}
related: there's another question that asks what enables pointer types to be used where closure types are expected:
如果闭包不捕获任何局部变量,则可以将其强制转换为函数指针。
不捕获任何变量的闭包实际上与普通函数相同,这听起来像是。此行为在 RFC 1558 中定义,它表示:
A closure that does not move, borrow, or otherwise access (capture) local variables should be coercable to a function pointer (
fn
).
所以 |n| n
可以被强制转换,因为它不捕获任何局部变量,但是 |n| n + a
不能被转换,因为它从外部环境捕获变量 a
。