1 // Rust-101, Part 10: Closures
2 // ===========================
7 //@ Assume we want to write a function that does *something* on, say, every digit of a `BigInt`.
8 //@ We will then need a way to express the action that we want to be taken, and to pass this to
9 //@ our function. In Rust, a natural first attempt to express this is to have a trait for it.
11 // So, let us define a trait that demands that the type provides some method `do_action` on digits.
12 //@ This immediately raises the question: How do we pass `self` to that function? Owned, shared borrow,
13 //@ or mutable borrow? The typical strategy to answer this question is to use the strongest
14 //@ type that still works. Certainly, passing `self` in owned form does not work: Then the function
15 //@ would consume `self`, and we could not call it again, on the second digit. So let's go with a mutable borrow.
17 fn do_action(&mut self, digit: u64);
20 // Now we can write a function that takes some `a` of a type `A` such that we can call `do_action` on `a`, passing it every digit.
22 fn act_v1<A: Action>(&self, mut a: A) {
23 //@ Remember that the `mut` above is just an annotation to Rust, telling it that we're okay with `a` being mutated.
24 //@ Calling `do_action` on `a` takes a mutable borrow, so mutation could indeed happen.
26 a.do_action(digit); /*@*/
31 //@ As the next step, we need to come up with some action, and write an appropriate implementation of `Action` for it.
32 //@ So, let's say we want to print every digit, and to make this less boring, we want the digits to be prefixed by some
33 //@ arbitrary string. `do_action` has to know this string, so we store it in `self`.
34 struct PrintWithString {
38 impl Action for PrintWithString {
39 // Here we perform the actual printing of the prefix and the digit. We're not making use of our ability to
40 // change `self` here, but we could replace the prefix if we wanted.
41 fn do_action(&mut self, digit: u64) {
42 println!("{}{}", self.prefix, digit); /*@*/
46 // Finally, this function takes a `BigInt` and a prefix, and prints the digits with the given prefix.
47 //@ It does so by creating an instance of `PrintWithString`, giving it the prefix, and then passing that to `act_v1`.
48 //@ Since `PrintWithString` implements `Action`, Rust now knows what to do.
49 fn print_with_prefix_v1(b: &BigInt, prefix: String) {
50 let my_action = PrintWithString { prefix: prefix };
54 // Here's a small main function, demonstrating the code above in action. Remember to edit `main.rs` to run it.
56 let bignum = BigInt::new(1 << 63) + BigInt::new(1 << 16) + BigInt::new(1 << 63);
57 print_with_prefix_v1(&bignum, "Digit: ".to_string());
61 //@ Now, as it turns out, this pattern of describing some form of an action, that can carry in additional data, is very common.
62 //@ In general, this is called a *closure*. Closures take some arguments and produce a result, and they have an *environment*
63 //@ they can use, which corresponds to the type `PrintWithString` (or any other type implementing `Action`). Again we have the
64 //@ choice of passing this environment in owned or borrowed form, so there are three traits for closures in Rust: `Fn`-closures
65 //@ get a shared borrow, `FnMut`-closures get a mutable borrow, and `FnOnce`-closures consume their environment (and can hence
66 //@ be called only once). The syntax for a closure trait which takes arguments of type `T1`, `T2`, ... and returns something
67 //@ of type `U` is `Fn(T1, T2, ...) -> U`.
69 // This defines `act` very similar to above, but now we demand `A` to be the type of a closure that mutates its borrowed environment,
70 // takes a digit, and returns nothing.
72 fn act<A: FnMut(u64)>(&self, mut a: A) {
74 // We can call closures as if they were functions - but really, what's happening here is translated to essentially what we wrote above, in `act_v1`.
80 // Now that we saw how to write a function that operates on closures, let's see how to write a closure.
81 pub fn print_with_prefix(b: &BigInt, prefix: String) {
82 //@ The syntax for closures is `|arg1, arg2, ...| code`. Notice that the closure can reference variables like `prefix` that it did not
83 //@ take as argument - variables that happen to be present *outside* of the closure. We say that the closure *captures*
84 //@ variables. Rust will now automatically create a type (like `PrintWithStruct`) for the environment of the closure
85 //@ with fields for every captured variable, implement the closure trait for this type such that the action performed
86 //@ is given by the code of the closure, and finally it will instantiate the environment type here at the definition site
87 //@ of the closure and fill it appropriately.
88 b.act(|digit| println!("{}{}", prefix, digit) );
90 // You can change `main` to call this function, and you should notice - nothing, no difference in behavior.
91 // But we wrote much less boilerplate code!
93 // Remember that we decided to use the `FnMut` trait above? This means our closure could actually mutate its environment.
94 // For example, we can use that to count the digits as they are printed.
95 pub fn print_and_count(b: &BigInt) {
96 let mut count: usize = 0;
97 //@ This time, the environment will contain a field of type `&mut usize`, that will be initialized with a mutable borrow of
98 //@ `count`. The closure, since it mutably borrows its environment, is able to access this field and mutate `count`
99 //@ through it. Once `act` returns, the closure is destroyed and the borrow of `count` ends. Because closures compile down
100 //@ to normal types, all the borrow checking continues to work as usually, and we cannot accidentally leak a closure somewhere
101 //@ that still contains, in its environment, a borrow that has ended.
102 b.act(|digit| { println!("{}: {}", count, digit); count = count +1; } );
103 println!("There are {} digits", count);
106 // ## Fun with iterators and closures
107 //@ If you are familiar with functional languages, you are probably aware that one can have lots of fun with iterators and closures.
108 //@ Rust provides a whole lot of methods on iterators that allow us to write pretty functional-style list manipulation.
110 // Let's say we want to write a function that increments every entry of a `Vec` by some number, then looks for numbers larger than some threshold, and prints them.
111 fn inc_print_even(v: &Vec<i32>, offset: i32, threshold: i32) {
112 //@ `map` takes a closure that is applied to every element of the iterator. `filter` removes elements
113 //@ from the iterator that do not pass the test given by the closure.
115 //@ Since all these closures compile down to the pattern described above, there is actually no heap allocation going on here. This makes
116 //@ closures very efficient, and it makes optimization fairly trivial: The resulting code will look like you hand-rolled the loop in C.
117 for i in v.iter().map(|n| *n + offset).filter(|n| *n > threshold) {
122 // Sometimes it is useful to know both the position of some element in a list, and its value. That's where the `enumerate` function helps.
123 fn print_enumerated<T: fmt::Display>(v: &Vec<T>) {
124 //@ `enumerate` turns an iterator over `T` into an iterator over `(usize, T)`, where the first element just counts the position in the iterator.
125 //@ We can do pattern matching right in the loop header to obtain names for both the position, and the value.
126 for (i, t) in v.iter().enumerate() {
127 println!("Position {}: {}", i, t);
131 // And as a final example, one can also collect all elements of an iterator, and put them, e.g., in a vector.
132 fn filter_vec_by_divisor(v: &Vec<i32>, divisor: i32) -> Vec<i32> {
133 //@ Here, the return type of `collect` is inferred based on the return type of our function. In general, it can return anything implementing
134 //@ [`FromIterator`](https://doc.rust-lang.org/stable/std/iter/trait.FromIterator.html). Notice that `iter` gives us an iterator over
135 //@ borrowed `i32`, but we want to own them for the result, so we insert a `map` to dereference.
136 v.iter().map(|n| *n).filter(|n| *n % divisor == 0).collect() /*@*/
139 // **Exercise 10.1**: Look up the [documentation of `Iterator`](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html) to learn about more functions
140 // that can act on iterators. Try using some of them. What about a function that sums the even numbers of an iterator? Or a function that computes the
141 // product of those numbers that sit at odd positions? A function that checks whether a vector contains a certain number? Whether all numbers are
142 // smaller than some threshold? Be creative!
144 //@ [index](main.html) | [previous](part09.html) | [raw source](https://www.ralfj.de/git/rust-101.git/blob_plain/HEAD:/workspace/src/part10.rs) | [next](part11.html)