gpt4 book ai didi

rust - 将代码拆分为文件时,实现特征不起作用

转载 作者:行者123 更新时间:2023-11-29 07:54:02 25 4
gpt4 key购买 nike

我在模块化代码时遇到了一个简单的 Rust 问题。

以下作品:

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());

我得到一个编译错误:

error: type a::A does not implement any method in scope named bar

我有点疑惑。

我正在使用:rustc 0.12.0-pre-nightly (0bdac78da 2014-09-01 21:31:00 +0000)

最佳答案

Trait B 必须在范围内,只要你想在实现它的对象上调用它的方法。您可能忘记将 B 导入到您使用 A 的文件中:

// At the top:
use b::B;

// Anywhere:
let test = a::A { foo: 5 };
println!("{}", test.bar());

This答案解释了为什么需要这样做。

关于rust - 将代码拆分为文件时,实现特征不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25815625/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com