我正在尝试在 Rust 中重载 右移运算符 (>>
),以 实现一个 Maybe 绑定。
enum Maybe<T> {
Nothing,
Just(T)
}
/// Maybe bind. For example:
///
/// ```
/// Just(1) >> |x| Just(1 + x) >> |x| Just(x * 2)
/// ```
impl<'a, T, U> Shr<|&T|: 'a -> Maybe<U>, Maybe<U>> for Maybe<T> {
fn shr(&self, f: &|&T| -> Maybe<U>) -> Maybe<U> {
match *self {
Nothing => Nothing,
Just(ref x) => (*f)(x)
}
}
}
fn main() {}
然而,在尝试调用闭包时,我遇到了一个错误:
<anon>:15:28: 15:32 error: closure invocation in a `&` reference
<anon>:15 Just(ref x) => (*f)(x)
^~~~
error: aborting due to previous error
playpen: application terminated with error code 101
Program ended.
为什么调用借用闭包是错误的,如何解决这个问题并实现绑定?
我在stackoverflow上找到了一个类似的问题,但自那以后rust发生了足够的变化,以至于它不再起作用。
Option.and_then
所做的(尽管它会消耗self
,因此能够通过值而不是引用传递对象,这显然更优)? - Chris Morgan