study_example/advance_feature/
advanced_function_closures.rs

1fn add_one(x: i32) -> i32 {
2    x + 1
3}
4
5fn do_twice(f: fn(i32) -> i32, arg: i32) -> i32 {
6    f(arg) + f(arg)
7}
8
9/// 运行结果如下
10/// ```txt
11/// do_twice answer: 8
12/// ```
13fn function_pointer() {
14    let answer = do_twice(add_one, 3);
15    println!("do_twice answer: {answer}");
16}
17
18/// 运行结果如下
19/// ```txt
20/// list of strings: ["1", "2", "3"]
21/// ```
22fn iterator_map_usage_closures() {
23    let list_of_numbers = vec![1, 2, 3];
24    let list_of_strings: Vec<String> = list_of_numbers.iter().map(|i| i.to_string()).collect();
25    println!("list of strings: {:?}", list_of_strings);
26}
27
28/// 运行结果如下
29/// ```txt
30/// list of strings: ["1", "2", "3"]
31/// ```
32fn iterator_map_usage_fn_pointer() {
33    let list_of_numbers = vec![1, 2, 3];
34    let list_of_strings: Vec<String> = list_of_numbers.iter().map(ToString::to_string).collect();
35    println!("list of strings: {:?}", list_of_strings);
36}
37
38/// 运行结果如下
39/// ```txt
40/// list of status: [Value(0), Value(1), Value(2), Value(3), Value(4)]
41/// ```
42fn init_enum_type() {
43    #[derive(Debug)]
44    enum Status {
45        Value(u32),
46        Stop,
47    }
48    let list_of_status: Vec<Status> = (0u32..5).map(Status::Value).collect();
49    println!("list of status: {:?}", list_of_status);
50}
51
52/// 编译报如下的错
53/// error[E0746]: return type cannot have an unboxed trait object
54///  --> study-example/src/advance_feature/advanced_function_closures.rs:52:24
55///   |
56/// 52 | fn return_closure() -> dyn Fn(i32) -> i32 {
57///    |                        ^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
58/*fn return_closure() -> dyn Fn(i32) -> i32 {
59    |x| x + 1
60}*/
61
62fn return_closure() -> Box<dyn Fn(i32) -> i32> {
63    Box::new(|x| x + 1)
64}
65
66/// 运行结果如下
67/// ```txt
68/// return_closure i = 32: 33
69/// ```
70pub fn advanced_function_closures_study() {
71    function_pointer();
72    iterator_map_usage_closures();
73    iterator_map_usage_fn_pointer();
74    init_enum_type();
75    let f = return_closure();
76    println!("return_closure i = 32: {}", f(32));
77}