How to reference a constant in a test in the same lib.rs file in Rust?

Viewed 538

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?

2 Answers

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}.

Related