functional-programing/closure #359
Replies: 7 comments 6 replies
-
Beta Was this translation helpful? Give feedback.
-
答案在哪里 |
Beta Was this translation helpful? Give feedback.
-
为什么第二题的assertion中count == 0 |
Beta Was this translation helpful? Give feedback.
-
有没有大佬知到我这个为什么错了,一直提示泛型 struct Cacher<K, V, T>
where
T: Fn(K) -> V,
K: Clone
{
query: T,
value: Option<V>,
}
impl<K, V, T> Cacher<K, V, T>
where
T: Fn(K) -> V,
K: Clone
{
fn new(query: T) -> Cacher<K, V, T> {
Cacher {
query,
value: None,
}
}
// 先查询缓存值 `self.value`,若不存在,则调用 `query` 加载
fn value(&mut self, arg: K) -> V {
match self.value {
Some(v) => v,
None => {
let v = (self.query)(arg);
self.value = Some(v);
v
}
}
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_cache() {
let cache = Cacher::new(|x| x + 1);
assert_eq!(cache.value(1), 2);
}
} 输出: Compiling playground v0.0.1 (/playground)
error[E0392]: parameter `K` is never used
--> src/lib.rs:1:15
|
1 | struct Cacher<K, V, T>
| ^ unused parameter
|
= help: consider removing `K`, referring to it in a field, or using a marker such as `PhantomData`
For more information about this error, try `rustc --explain E0392`. |
Beta Was this translation helpful? Give feedback.
-
给一个不需要Copy特性的写法 impl<T, E> Cacher<T, E>
} #[test]
} |
Beta Was this translation helpful? Give feedback.
-
第一题 /* Make it work with least amount of changes*/
fn main() {
let color = String::from("green");
let print = || println!("`color`: {}", color);
print();
print();
// `color` can be borrowed immutably again, because the closure only holds
// an immutable reference to `color`.
let _reborrow = &color;
println!("{}",color);
} 第二题 /* Make it work
- Dont use `_reborrow` and `_count_reborrowed`
- Dont modify `assert_eq`
*/
fn main() {
let mut count = 0;
let mut inc = move || {
count += 1;
println!("`count`: {}", count);
};
inc();
let _reborrow = &count;
inc();
// The closure no longer needs to borrow `&mut count`. Therefore, it is
// possible to reborrow without an error
let _count_reborrowed = &mut count;
assert_eq!(count, 0);
} 第三题 /* Make it work in two ways, none of them is to remove `take(movable)` away from the code
*/
fn main() {
let movable = Box::new(3);
let consume = || {
println!("`movable`: {:?}", movable);
take(movable);
};
consume();
// consume();
}
fn take<T>(_v: T) {} 第四题 fn main() {
let example_closure = |x| x;
let s = example_closure(String::from("hello"));
/* Make it work, only change the following line */
let n = example_closure(5.to_string());
} 第五题 /* Make it work by changing the trait bound, in two ways*/
fn fn_once<F>(func: F)
where
F: Fn(usize) -> bool,
{
println!("{}", func(3));
println!("{}", func(4));
}
fn main() {
let x = vec![1, 2, 3];
fn_once(|z|{z == x.len()})
} 第六题 fn main() {
let mut s = String::new();
let update_string = |str| s.push_str(str);
exec(update_string);
println!("{:?}",s);
}
/* Fill in the blank */
fn exec<'a, F: FnMut(&'a str)>(mut f: F) {
f("hello")
} 第七题 fn apply<F>(f: F) where
// The closure takes no input and returns nothing.
F: FnOnce() {
f();
} 第八题 /* Fill in the blank */
fn main() {
let mut s = String::new();
let update_string = |str| -> String {s.push_str(str); s };
exec(update_string);
}
fn exec<'a, F: FnOnce(&'a str) -> String>(mut f: F) {
f("hello");
} 第九题 /* Implement `call_me` to make it work */
fn call_me<F: Fn()>(f: F) {
f();
}
fn function() {
println!("I'm a function!");
}
fn main() {
let closure = || println!("I'm a closure!");
call_me(closure);
call_me(function);
} 第10题 /* Fill in the blank using two approaches,
and fix the error */
fn create_fn() -> Box<dyn Fn(i32) -> i32> {
let num = 5;
// How does the following closure capture the environment variable `num`
// &T, &mut T, T ?
Box::new(move |x| x + num)
}
fn main() {
let fn_plain = create_fn();
fn_plain(1);
} 第11题 fn main() {}
/* Fill in the blank and fix the error*/
fn factory(x:i32) -> Box<dyn Fn(i32) -> i32> {
let num = 5;
if x > 1{
Box::new(move |x| x + num)
} else {
Box::new(move |x| x + num)
}
} |
Beta Was this translation helpful? Give feedback.
-
done |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
functional-programing/closure
Learning Rust By Practice, narrowing the gap between beginner and skilled-dev with challenging examples, exercises and projects.
https://zh.practice.rs/functional-programing/closure.html
Beta Was this translation helpful? Give feedback.
All reactions