gpt4 book ai didi

rust - `#[cfg(test)]` 和 `#[cfg(feature = "test")]` 有什么区别?

转载 作者:行者123 更新时间:2023-12-02 18:07:47 33 4
gpt4 key购买 nike

我想了解 #[cfg(test)]#[cfg(feature = "test")] 之间的区别,最好通过示例进行演示。

最佳答案

#[cfg(test)] 标记仅当启用 test 配置选项时才编译的内容,而 #[cfg(feature = "test ")] 标记仅当启用 feature = "test" 配置选项时才编译的内容。

When running cargo test, one of the things that happens is that rustc is passed the --test flag which (among other things) "enables the test cfg option".这通常用于仅在您想要运行测试时有条件地编译测试模块。

Features are something that cargo uses for general conditional compilation (and optional dependencies).

尝试运行:

#[cfg(feature="test")]
mod fake_test {
#[test]
fn fake_test() {
panic!("This function is NOT tested");
}
}

#[cfg(test)]
mod test {
#[test]
fn test() {
panic!("This function is tested");
}
}

输出将是:

running 1 test
test test::test ... FAILED

failures:

---- test::test stdout ----
thread 'test::test' panicked at 'This function is tested', src/lib.rs:13:9
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace


failures:
test::test

test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

这表明假测试模块没有启用。

关于rust - `#[cfg(test)]` 和 `#[cfg(feature = "test")]` 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72908829/

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