Start writing a part on closures
[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 read_one_line() -> String {
32     println!("Please enter a line of text.");
33     let mut stdin = io::stdin();
34     let mut prefix = "".to_string();
35     stdin.read_line(&mut prefix).unwrap();
36     prefix
37 }
38
39 pub fn main_v1() {
40     let prefix = read_one_line();
41     let my_action = PrintWithString { prefix: prefix };
42     let bignum = BigInt::new(1 << 63) + BigInt::new(1 << 16) + BigInt::new(1 << 63);
43     bignum.act_v1(my_action);
44 }
45
46 impl BigInt {
47     fn act<A: FnMut(u64)>(&self, mut a: A) {
48         for digit in self {
49             a(digit);
50         }
51     }
52 }
53
54 pub fn main() {
55     let prefix = read_one_line();
56     let bignum = BigInt::new(1 << 63) + BigInt::new(1 << 16) + BigInt::new(1 << 63);
57     bignum.act(|digit| println!("{}{}", prefix, digit) );
58 }
59
60 //@ [index](main.html) | [previous](part08.html) | [next](main.html)