]>
Commit | Line | Data |
---|---|---|
1 | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT | |
2 | // file at the top-level directory of this distribution and at | |
3 | // http://rust-lang.org/COPYRIGHT. | |
4 | // | |
5 | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or | |
6 | // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license | |
7 | // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your | |
8 | // option. This file may not be copied, modified, or distributed | |
9 | // except according to those terms. | |
10 | ||
11 | // A model for how the `Fn` traits could work. You can implement at | |
12 | // most one of `Go`, `GoMut`, or `GoOnce`, and then the others follow | |
13 | // automatically. | |
14 | ||
15 | // aux-build:go_trait.rs | |
16 | ||
17 | ||
18 | extern crate go_trait; | |
19 | ||
20 | use go_trait::{Go, GoMut, GoOnce, go, go_mut, go_once}; | |
21 | ||
22 | use std::rc::Rc; | |
23 | use std::cell::Cell; | |
24 | ||
25 | /////////////////////////////////////////////////////////////////////////// | |
26 | ||
27 | struct SomeGoableThing { | |
28 | counter: Rc<Cell<isize>> | |
29 | } | |
30 | ||
31 | impl Go for SomeGoableThing { | |
32 | fn go(&self, arg: isize) { | |
33 | self.counter.set(self.counter.get() + arg); | |
34 | } | |
35 | } | |
36 | ||
37 | /////////////////////////////////////////////////////////////////////////// | |
38 | ||
39 | struct SomeGoOnceableThing { | |
40 | counter: Rc<Cell<isize>> | |
41 | } | |
42 | ||
43 | impl GoOnce for SomeGoOnceableThing { | |
44 | fn go_once(self, arg: isize) { | |
45 | self.counter.set(self.counter.get() + arg); | |
46 | } | |
47 | } | |
48 | ||
49 | /////////////////////////////////////////////////////////////////////////// | |
50 | ||
51 | fn main() { | |
52 | let counter = Rc::new(Cell::new(0)); | |
53 | let mut x = SomeGoableThing { counter: counter.clone() }; | |
54 | ||
55 | go(&x, 10); | |
56 | assert_eq!(counter.get(), 10); | |
57 | ||
58 | go_mut(&mut x, 100); | |
59 | assert_eq!(counter.get(), 110); | |
60 | ||
61 | go_once(x, 1_000); | |
62 | assert_eq!(counter.get(), 1_110); | |
63 | ||
64 | let x = SomeGoOnceableThing { counter: counter.clone() }; | |
65 | ||
66 | go_once(x, 10_000); | |
67 | assert_eq!(counter.get(), 11_110); | |
68 | } |