当代码模块化时,我有一个简单的锈蚀问题。
以下工作:
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());
它打印5
,但一旦我模块化代码:
// 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());
我得到一个编译错误:
错误:类型
a::A
没有在名为bar
的作用域中实现任何方法
我有点困惑。
我在用:rustc 0.12.0-pre-nightly (0bdac78da 2014-09-01 21:31:00 +0000)
发布于 2014-09-12 19:51:09
每当您想在实现特性B
的对象上调用它的方法时,它必须在作用域中。您可能忘记将B
导入到使用A
的文件中。
// At the top:
use b::B;
// Anywhere:
let test = a::A { foo: 5 };
println!("{}", test.bar());
This的回答解释了为什么需要这样做。
https://stackoverflow.com/questions/25815625
复制相似问题