2012-07-31 10:27:51 -07:00
|
|
|
// Test cyclic detector when using trait instances.
|
2012-01-10 19:04:09 -08:00
|
|
|
|
2012-01-19 16:10:31 -08:00
|
|
|
enum Tree = TreeR;
|
2012-01-10 19:04:09 -08:00
|
|
|
type TreeR = @{
|
2012-08-20 12:23:37 -07:00
|
|
|
mut left: Option<Tree>,
|
|
|
|
mut right: Option<Tree>,
|
2012-01-10 19:04:09 -08:00
|
|
|
val: to_str
|
|
|
|
};
|
|
|
|
|
2012-07-31 10:27:51 -07:00
|
|
|
trait to_str {
|
2012-07-13 22:57:48 -07:00
|
|
|
fn to_str() -> ~str;
|
2012-01-10 19:04:09 -08:00
|
|
|
}
|
|
|
|
|
2012-08-20 12:23:37 -07:00
|
|
|
impl <T: to_str> Option<T>: to_str {
|
2012-07-13 22:57:48 -07:00
|
|
|
fn to_str() -> ~str {
|
2012-08-06 12:34:08 -07:00
|
|
|
match self {
|
2012-08-20 12:23:37 -07:00
|
|
|
None => { ~"none" }
|
|
|
|
Some(t) => { ~"some(" + t.to_str() + ~")" }
|
2012-01-10 19:04:09 -08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2012-08-07 18:10:06 -07:00
|
|
|
impl int: to_str {
|
2012-07-13 22:57:48 -07:00
|
|
|
fn to_str() -> ~str { int::str(self) }
|
2012-01-10 19:04:09 -08:00
|
|
|
}
|
|
|
|
|
2012-08-07 18:10:06 -07:00
|
|
|
impl Tree: to_str {
|
2012-07-13 22:57:48 -07:00
|
|
|
fn to_str() -> ~str {
|
2012-06-04 10:44:19 -07:00
|
|
|
let l = self.left, r = self.right;
|
2012-08-22 17:24:52 -07:00
|
|
|
fmt!("[%s, %s, %s]", self.val.to_str(),
|
|
|
|
l.to_str(), r.to_str())
|
2012-01-10 19:04:09 -08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2012-07-13 22:57:48 -07:00
|
|
|
fn foo<T: to_str>(x: T) -> ~str { x.to_str() }
|
2012-01-12 16:57:30 +01:00
|
|
|
|
2012-01-10 19:04:09 -08:00
|
|
|
fn main() {
|
2012-08-20 12:23:37 -07:00
|
|
|
let t1 = Tree(@{mut left: None,
|
|
|
|
mut right: None,
|
2012-01-10 19:04:09 -08:00
|
|
|
val: 1 as to_str });
|
2012-08-20 12:23:37 -07:00
|
|
|
let t2 = Tree(@{mut left: Some(t1),
|
|
|
|
mut right: Some(t1),
|
2012-01-10 19:04:09 -08:00
|
|
|
val: 2 as to_str });
|
2012-07-13 22:57:48 -07:00
|
|
|
let expected = ~"[2, some([1, none, none]), some([1, none, none])]";
|
2012-01-12 16:57:30 +01:00
|
|
|
assert t2.to_str() == expected;
|
|
|
|
assert foo(t2 as to_str) == expected;
|
2012-08-20 12:23:37 -07:00
|
|
|
t1.left = Some(t2); // create cycle
|
2012-01-10 19:04:09 -08:00
|
|
|
}
|