make it so that I can actually run stuff that relies on the solution of exercises
[rust-101.git] / src / part10.rs
1 // Rust-101, Part 09: Closures (WIP)
2 // =================================
3
4 use std::io::prelude::*;
5 use std::io;
6
7 use part05::BigInt;
8
9 trait Action {
10     fn do_action(&mut self, digit: u64);
11 }
12
13 impl BigInt {
14     fn act_v1<A: Action>(&self, mut a: A) {
15         for digit in self {
16             a.do_action(digit);
17         }
18     }
19 }
20
21 struct PrintWithString {
22     prefix: String,
23 }
24
25 impl Action for PrintWithString {
26     fn do_action(&mut self, digit: u64) {
27         println!("{}{}", self.prefix, digit);
28     }
29 }
30
31 fn print_with_prefix_v1(b: &BigInt, prefix: String) {
32     let my_action = PrintWithString { prefix: prefix };
33     b.act_v1(my_action);
34 }
35
36 pub fn main() {
37     let bignum = BigInt::new(1 << 63) + BigInt::new(1 << 16) + BigInt::new(1 << 63);
38     print_with_prefix_v1(&bignum, "Digit: ".to_string());
39 }
40
41 impl BigInt {
42     fn act<A: FnMut(u64)>(&self, mut a: A) {
43         for digit in self {
44             a(digit);
45         }
46     }
47 }
48
49 pub fn print_with_prefix(b: &BigInt, prefix: String) {
50     b.act(|digit| println!("{}{}", prefix, digit) );
51 }
52
53 //@ [index](main.html) | [previous](part08.html) | [next](main.html)