[英]How to reference a constant in a test in the same lib.rs file in Rust?
I have a constants defined in a lib.rs as follows:我在 lib.rs 中定义了一个常量,如下所示:
const GREEN: LedColor = LedColor(0, 255, 0);
In the same lib.rs file I also have tests trying to use GREEN as follows:在同一个 lib.rs 文件中,我也有尝试使用 GREEN 的测试,如下所示:
#[cfg(test)]
mod tests {
use {OFF, YELLOW, RED, GREEN};
#[test]
fn some_test() {//...}
But running cargo test gives an error such as:但是运行 cargo test 会出现错误,例如:
no GREEN in path
路径中没有绿色
How do I reference the constant GREEN in a test that's in the same file?如何在同一文件中的测试中引用常量 GREEN?
You need to use the super
keyword , to reference the parent module.您需要使用
super
关键字来引用父模块。
The module tests
is actually crate::tests
, which means GREEN
the way you've written it there is really crate::tests::GREEN
.模块
tests
实际上是crate::tests
,这意味着GREEN
你写它的方式真的是crate::tests::GREEN
。 That doesn't exist, as GREEN
is defined in the parent module.那不存在,因为
GREEN
在父模块中定义。 So you need:所以你需要:
#[cfg(test)]
mod tests {
use super::{OFF, YELLOW, RED, GREEN};
}
These are considered private so a normal use crate::{names}
wouldn't work.这些被认为是私有的,因此正常
use crate::{names}
将不起作用。
You can use use super::*
( *
makes them all available, as a shorthand) which brings in private names from the parent module.您可以使用
use super::*
( *
使它们全部可用,作为简写),它从父模块引入私有名称。 (though this isn't documented from what I could find) (虽然这不是我能找到的记录)
If you don't mind making them public, you can add pub
and then use use crate::{names}
.如果您不介意将它们公开,您可以添加
pub
然后使用use crate::{names}
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.