简体   繁体   中英

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:

const GREEN: LedColor = LedColor(0, 255, 0);

In the same lib.rs file I also have tests trying to use GREEN as follows:

#[cfg(test)]
mod tests {
    use {OFF, YELLOW, RED, GREEN};
    #[test]
    fn some_test() {//...}

But running cargo test gives an error such as:

no GREEN in path

How do I reference the constant GREEN in a test that's in the same file?

You need to use the super keyword , to reference the parent module.

The module tests is actually crate::tests , which means GREEN the way you've written it there is really crate::tests::GREEN . That doesn't exist, as GREEN is defined in the parent module. 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.

You can use use super::* ( * makes them all available, as a shorthand) which brings in private names from the parent module. (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} .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM