2011-08-11 18:02:55 -05:00
|
|
|
// Sanity-check the code examples that appear in the object system
|
|
|
|
// documentation.
|
2011-08-15 18:54:02 -05:00
|
|
|
use std;
|
2011-12-13 18:25:51 -06:00
|
|
|
import comm::chan;
|
|
|
|
import comm::send;
|
|
|
|
import comm::port;
|
2011-08-11 18:02:55 -05:00
|
|
|
|
|
|
|
fn main() {
|
|
|
|
|
|
|
|
// Ref.Item.Obj
|
|
|
|
obj counter(state: @mutable int) {
|
2011-08-19 17:16:48 -05:00
|
|
|
fn incr() { *state += 1; }
|
|
|
|
fn get() -> int { ret *state; }
|
|
|
|
}
|
2011-08-11 18:02:55 -05:00
|
|
|
|
|
|
|
let c: counter = counter(@mutable 1);
|
|
|
|
|
|
|
|
c.incr();
|
|
|
|
c.incr();
|
2011-08-19 17:16:48 -05:00
|
|
|
assert (c.get() == 3);
|
2011-08-11 18:02:55 -05:00
|
|
|
|
|
|
|
obj my_obj() {
|
2011-08-19 17:16:48 -05:00
|
|
|
fn get() -> int { ret 3; }
|
|
|
|
fn foo() -> int {
|
2011-08-11 18:02:55 -05:00
|
|
|
let c = self.get();
|
|
|
|
ret c + 2; // returns 5
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
let o = my_obj();
|
2011-08-19 17:16:48 -05:00
|
|
|
assert (o.foo() == 5);
|
2011-08-11 18:02:55 -05:00
|
|
|
|
|
|
|
// Ref.Type.Obj
|
2011-08-19 17:16:48 -05:00
|
|
|
type taker =
|
|
|
|
obj {
|
|
|
|
fn take(int);
|
|
|
|
};
|
2011-08-11 18:02:55 -05:00
|
|
|
|
|
|
|
obj adder(x: @mutable int) {
|
2011-08-19 17:16:48 -05:00
|
|
|
fn take(y: int) { *x += y; }
|
2011-08-11 18:02:55 -05:00
|
|
|
}
|
|
|
|
|
2011-08-25 13:20:43 -05:00
|
|
|
obj sender(c: chan<int>) {
|
2011-11-03 04:57:54 -05:00
|
|
|
fn take(z: int) { send(c, copy z); }
|
2011-08-11 18:02:55 -05:00
|
|
|
}
|
|
|
|
|
2011-08-19 17:16:48 -05:00
|
|
|
fn give_ints(t: taker) { t.take(1); t.take(2); t.take(3); }
|
2011-08-11 18:02:55 -05:00
|
|
|
|
2011-08-25 13:20:43 -05:00
|
|
|
let p = port();
|
2011-08-11 18:02:55 -05:00
|
|
|
|
|
|
|
let t1: taker = adder(@mutable 0);
|
2011-08-25 13:20:43 -05:00
|
|
|
let t2: taker = sender(chan(p));
|
2011-08-11 18:02:55 -05:00
|
|
|
|
|
|
|
give_ints(t1);
|
|
|
|
give_ints(t2);
|
|
|
|
}
|
|
|
|
|