Reputation: 30312
I have a simple Rust problem that arises when modularizing the code.
The following works:
pub trait B {
fn bar(&self) -> int;
}
pub struct A {
foo: int
}
impl B for A {
fn bar(&self) -> int { 5 }
}
// Later...
let a = A { foo: 5 };
println!("{}", a.bar());
It prints 5
, but as soon as I modularize the code:
// lib.rs
mod a;
mod b;
// b.rs
pub trait B {
fn bar(&self) -> int;
}
// a.rs
use b::B;
pub struct A {
foo: int
}
impl B for A {
fn bar(&self) -> int { 5 }
}
// Anywhere:
let test = a::A { foo: 5 };
println!("{}", test.bar());
I get a compilation error:
error: type
a::A
does not implement any method in scope namedbar
I'm slightly puzzled.
I'm using: rustc 0.12.0-pre-nightly (0bdac78da 2014-09-01 21:31:00 +0000)
Upvotes: 7
Views: 3026
Reputation: 1838
Trait B
must be in scope whenever you want to call its methods on an object implementing it. You likely forgot to import B
into the file where you use A
:
// At the top:
use b::B;
// Anywhere:
let test = a::A { foo: 5 };
println!("{}", test.bar());
This answer explains why that's needed.
Upvotes: 6