我仍在内化 Rust 中的闭包以及如何最好地使用它们,所以这个问题可能有些模糊,并且可能会有一些愚蠢的子问题。我基本上是在寻找合适的习语,甚至可能改变我思考如何在 Rust 中做一些事情的方式。
Rust 书Cacher
在关于闭包的章节中有一个简单的例子:
struct Cacher<T>
where
T: Fn(u32) -> u32,
{
calculation: T,
value: Option<u32>,
}
impl<T> Cacher<T>
where
T: Fn(u32) -> u32,
{
fn new(calculation: T) -> Cacher<T> {
Cacher {
calculation,
value: None,
}
}
fn value(&mut self, arg: u32) -> u32 {
match self.value {
Some(v) => v,
None => {
let v = (self.calculation)(arg);
self.value = Some(v);
v
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
它应该像这样使用:
let mut …
Run Code Online (Sandbox Code Playgroud) trait FooTrait {}
struct FooStruct;
impl FooTrait for FooStruct {}
fn main() {
let maybe_struct: Option<FooStruct> = None;
// Does not compile, "expected trait FooTrait, found struct `FooStruct`"
// let maybe_trait: Option<Box<FooTrait>> = maybe_struct.map(Box::new);
// Compiles fine
let maybe_trait: Option<Box<FooTrait>> = match maybe_struct {
Some(s) => Some(Box::new(s)),
None => None,
};
}
Run Code Online (Sandbox Code Playgroud)
Rustc 1.23.0.为什么第一种方法不能编译?我错过了一些明显的东西,或者......嗯?
rust ×2