gpt4 book ai didi

rust - 如何在 doctest 中使用自定义模块?

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

mod simulation;

use simulation::factory::FactoryType;

main.rs 中运行良好,但在 simulation/factory.rs 中的 doctest 中运行不正常:

impl product_type::ProductType for FactoryType {
/// Lorem Ipsum
///
/// # Examples
///
/// ```
/// use simulation::factory::FactoryType;
///
/// ...
/// ```
fn human_id(&self) -> &String {
...
}
}

cargo test 给我错误

---- simulation::factory::human_id_0 stdout ----
<anon>:2:9: 2:19 error: unresolved import `simulation::factory::FactoryType`. Maybe a missing `extern crate simulation`?
<anon>:2 use simulation::factory::FactoryType;
^~~~~~~~~~
error: aborting due to previous error
thread 'simulation::factory::human_id_0' panicked at 'Box<Any>', /home/rustbuild/src/rust-buildbot/slave/stable-dist-rustc-linux/build/src/libsyntax/diagnostic.rs:192

如何让 doctest 发挥作用?

最佳答案

当您编写文档测试时,您必须充当代码的用户。鉴于这些文件:

src/lib.rs

pub mod simulation {
pub mod factory {
pub struct FactoryType;

impl FactoryType {
/// ```
/// use foo::simulation::factory::FactoryType;
///
/// let f = FactoryType;
/// assert_eq!(42, f.human_id())
/// ```
pub fn human_id(&self) -> u8 { 41 }
}
}
}

src/main.rs

extern crate foo;
use foo::simulation::factory::FactoryType;

fn main() {
let f = FactoryType;
println!("{}", f.human_id());
}

一切正常。请注意,在 ma​​in.rs 中,您必须说 extern crate,然后您的所有引用都需要包含 crate 名称。 doctest 是相同的,除了 extern crate 会自动包含在内。

关于rust - 如何在 doctest 中使用自定义模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32473295/

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