rust - Option::map(FnOnce) 似乎不接受 FnOnce ...?

标签 rust

我对 Option::map() 有点困惑。 documentation表示它接受 FnOnce

如果是这样,为什么ab会导致编译错误?

let mut v = 3;

let mut a: &FnOnce(u32) -> u32 = &|x: u32| { v = x; x };
let mut b: &FnMut(u32) -> u32 = &|x: u32| { x };
let mut c: &Fn(u32) -> u32 = &|x: u32| { x };

let o = Option::Some(3);

o.map(a); // trait bound `std::ops::FnOnce(u32) -> u32: std::ops::Fn<(u32,)>` is not satisfied
o.map(b); // trait bound `std::ops::FnMut(u32) -> u32: std::ops::Fn<(u32,)>` is not satisfied
o.map(c); // works

根据this post,它们不应该全部实现FnOnce,包括ab 吗? ?

最佳答案

问题是您不是直接使用 FnOnce 调用 Option::map,而是使用 &FnOnce

但是如果你看一下 implementors for FnOnce ,您会注意到虽然 FnOnce 是为 &Fn 实现的,但它不是为 &FnOnce&FnMut 实现的。 要了解原因,请考虑以下几点:

let a: &FnOnce(u32) -> u32 = &|x: u32| { v = x; x };
let b: &FnOnce(u32) -> u32 = a;

a(42); // would be allowed if `&FnOnce: FnOnce`, moves `a`
       // actually gives: 
       // error[E0507]: cannot move out of borrowed content
a(6);  // would not be allowed as `a` was moved
b(7);  // would be allowed if `&FnOnce: FnOnce`
       // oh no! this calls the function again!

关于rust - Option::map(FnOnce) 似乎不接受 FnOnce ...?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47933779/

相关文章:

error-handling - 如何以惯用的 Rust 方式处理来自 libc 函数的错误?

rust - 如何错误处理字符串到浮点转换

rust - 为什么 '?' 运算符使用 From 而不是 Into?

rust - 如何正确退出 mpsc::Receiver 上的线程阻塞

rust - 如何与 Rust 中的向量元素匹配?

rust - 为什么 `Arc<Mutex<dyn MyTrait>>`自动获得静态生命周期?

rust - 删除 crate 功能

rust - 将 `usize` 转换为 `&str` 的最佳方法是什么?

hash - 使用 decl_storage 时,为什么在 StorageMap 中使用 blake2_256 以外的哈希算法

multithreading - 过程宏是否在一个线程中编译?