我正在编写带有单元测试的 Rust 库(从 cargo 生成)。
我想使用 extern crate maplit在我的单元测试中能够使用类似 JavaScript 的 hashmap 文字。我不想在我的库代码中使用 maplit。
maplit 提供了一个显然必须使用#[macro_use] 激活的宏。我能够使这一切正常工作的唯一方法是将它放在 lib.rs
的顶部:
#[cfg(test)] #[macro_use] extern crate maplit;
// my crate-specific stuff
此时我意识到我不知道#[cfg(test)] 到底做了什么。我在我的测试中使用它。按照惯例,这些包含在库代码中,如下所示:
// some library code
#[cfg(test)]
mod test {
use super::*;
// tests here
}
我原以为 #[cfg(test)] 行将文件(或 block ?)末尾之前的内容标记为仅适用于测试配置。
如果是这样,那么将此指令放在 lib.rs
的顶部似乎是个问题。当我编译一个发行版时,我的整个库不会被删除吗?
我试图找到关于#[cfg(test)] 到底做了什么的文档,但无济于事。
最佳答案
#[....]
上面是一个Rust Attribute这就像其他语言中的注释。例如;在 Java 中,我们有 @Annotation(....)
用于方法和类。与注释不同,rust 属性可以是遵循属性语法的表达式。
#[cfg(....)]
上面是一个compiler configuration属性。 cfg()
是众多 built-in attributes 之一.
#[cfg(test)]
上面的代码告诉 Rust 编译器,只有当 test
配置事件时,才应该编译以下代码。您可以拥有其他配置属性,例如 debug
、windows
或 features。
#[cfg(test)] #[macro_use] extern crate maplit;
与
相同#[cfg(test)]
#[macro_use]
extern crate maplit;
如果 test
配置激活,它告诉 Rust 编译器只编译下一行,下一行告诉 Rust 只使用来自下面 crate 的宏。
If so, then putting this directive at the top of lib.rs seems like a problem. Won't my entire library be dropped when I compile a distribution?
#[cfg(...)]
属性仅将编译器条件应用于它所附加的事物。
当您将属性放在文件顶部后跟一个空格时。该属性附加到当前模块或包装箱。
如文档示例中所示,crate_type
应用于整个文件:
// General metadata applied to the enclosing module or crate.
#![crate_type = "lib"]
// A function marked as a unit test
#[test]
fn test_foo() {
/* ... */
}
// A conditionally-compiled module
#[cfg(target_os = "linux")]
mod bar {
/* ... */
}
// A lint attribute used to suppress a warning/error
#[allow(non_camel_case_types)]
type int8_t = i8;
// Inner attribute applies to the entire function.
fn some_unused_variables() {
#![allow(unused_variables)]
let x = ();
let y = ();
let z = ();
}
关于rust - #[cfg(test)] 放在 lib.rs 的顶部时会做什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58652318/