404 #191
404
#191
Replies: 8 comments 9 replies
-
404了,初学rust尝试写了个: struct Cacher<T, F>
where
T: Fn(F) -> F,
F: Copy,
{
query: T,
value: Option<F>,
}
impl<T, F> Cacher<T, F>
where
T: Fn(F) -> F,
F: Copy,
{
fn new(query: T) -> Cacher<T, F> {
Cacher { query, value: None }
}
// 先查询缓存值 `self.value`,若不存在,则调用 `query` 加载
fn value(&mut self, arg: F) -> F {
match self.value {
Some(v) => v,
None => {
let v = (self.query)(arg);
self.value = Some(v);
v
}
}
}
}
fn main() {
let mut c = Cacher::new(|x| x);
println!("{}", c.value(32));
let mut c = Cacher::new(|x| x);
println!("{}", c.value("abc"));
} |
Beta Was this translation helpful? Give feedback.
5 replies
-
struct Cacher<T, E: Copy> impl<T, E: Copy> Cacher<T, E>
} |
Beta Was this translation helpful? Give feedback.
0 replies
-
初学者,只能自己琢磨了 #[test]
|
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
404
Learning Rust By Practice, narrowing the gap between beginner and skilled-dev with challenging examples, exercises and projects.
https://zh.practice.rs/std/String.html
Beta Was this translation helpful? Give feedback.
All reactions