Add [Closure] chapter

This commit is contained in:
sunface 2022-03-31 13:49:17 +08:00
parent 8220143688
commit 562eb9247f
4 changed files with 91 additions and 6 deletions

View File

@ -53,9 +53,9 @@
- [basic](lifetime/basic.md)
- [&'static and T: 'static](lifetime/static.md)
- [advanced](lifetime/advance.md)
- [Functional programing TODO](functional-programing/intro.md)
- [Functional programing](functional-programing/intro.md)
- [Closure](functional-programing/cloure.md)
- [Iterator](functional-programing/iterator.md)
- [Iterator TODO](functional-programing/iterator.md)
- [newtype and Sized TODO](newtype-sized.md)
- [Smart pointers TODO](smart-pointers/intro.md)
- [Box](smart-pointers/box.md)

View File

@ -328,10 +328,44 @@ fn main() {
## Closure as return types
Returning a closure is much harder than you may thought of.
10、🌟🌟
```rust,editable
/* Fill in the blank using two approches,
and fix the errror */
fn create_fn() -> __ {
let num = 5;
<!-- 2、
下面代码是Rust圣经课程中[闭包](http://course.rs/advance/functional-programing/closure.html#结构体中的闭包)章节的课内练习题答案:
// how does the following closure capture the evironment variable `num`
// &T, &mut T, T ?
|x| x + num
}
fn main() {
let fn_plain = create_fn();
fn_plain(1);
}
```
11、🌟🌟
```rust,editable
/* Fill in the blank and fix the error*/
fn factory(x:i32) -> __ {
let num = 5;
if x > 1{
move |x| x + num
} else {
move |x| x + num
}
}
```
## Closure in structs
**Example**
```rust
struct Cacher<T,E>
where
@ -378,4 +412,4 @@ fn call_with_different_values() {
assert_eq!(v2, 1);
}
``` -->
```

View File

@ -231,4 +231,55 @@ fn main() {
call_me(closure);
call_me(function);
}
```
10、
```rust
/* Fill in the blank and fix the errror */
// You can aslo use `impl FnOnce(i32) -> i32`
fn create_fn() -> impl Fn(i32) -> i32 {
let num = 5;
move |x| x + num
}
fn main() {
let fn_plain = create_fn();
fn_plain(1);
}
```
```rust
/* Fill in the blank and fix the errror */
fn create_fn() -> Box<dyn Fn(i32) -> i32> {
let num = 5;
// how does the following closure capture the evironment variable `num`
// &T, &mut T, T ?
Box::new(move |x| x + num)
}
fn main() {
let fn_plain = create_fn();
fn_plain(1);
}
```
11、
```rust
// Every closure has its own type. Even if one closure has the same representation as another, their types are different.
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)
}
}
fn main() {}
```

View File

@ -66,7 +66,7 @@ fn main() {
let _v: () = ();
let v = (2, 3);
assert_eq!(v, implicitly_ret_unit())
assert_eq!(v, implicitly_ret_unit());
println!("Success!")
}