rustc 1.0.0-nightly (d3732a12e 2015-02-06 23:30:17 +0000)
When reading the reference manual about type aliases, I (possibly erroneously) arrived at the conclusion that type-aliases are just a shortcut to save some typing. The following example proved me wrong though.
// type actually declares something like a new type with given memory layout
struct Foo {
a: u32,
};
impl Foo {
fn bark(&self) {
println!("Wuff {}", self.a);
}
fn id() -> &'static str {
"FOO"
}
}
assert_eq!(Foo::id(), "FOO");
let f = Foo { a: 1 };
f.bark();
type Bar = Foo;
// assert_eq!(!Bar::id(), "FOO");
// error: unresolved name `Bar::id`
// tests/lang.rs:628 assert_eq!(!Bar::id(), "FOO");
let b = Bar { a: 2 };
b.bark(); // this works though
impl Bar {
// This would add a similarly named implementation, that is difficult to call
// due to ambiguity.
// Interestingly, it also affects Foo, as well as Bar !!
// fn bark(&self) {
// println!("Grrrr {}", self.a);
// }
fn id() -> &'static str {
"BAR"
}
}
// b.bark(); // or f.bark();
// error: multiple applicable methods in scope [E0034]
// tests/lang.rs:625 f.bark();
// ^~~~~~
// tests/lang.rs:615:9: 617:10 note: candidate #1 is defined in an impl for the type `type_aliases::Foo`
// tests/lang.rs:615 fn bark(&self) {
// tests/lang.rs:616 println!("Wuff {}", self.a);
// tests/lang.rs:617 }
// tests/lang.rs:637:9: 639:10 note: candidate #2 is defined in an impl for the type `type_aliases::Foo`
// tests/lang.rs:637 fn bark(&self) {
// tests/lang.rs:638 println!("Grrrr {}", self.a);
assert_eq!(Bar::id(), "BAR");
It seems Bar
is a new type, which shares the memory layout of Foo
. It does inherit instance methods, but doesn’t inherit type methods. Interestingly, instance method implementations applied to Bar
also apply to Foo
.
Is it just me being unable to understand the documentation, or am I onto something here ?