Rust - Can't use enum in tests / can't use type on a child module

Viewed 108

I'm trying to use an enum inside tests in the same file, and it doesn't work. Here's a minimal example:

#[derive(PartialEq)]
enum Token {
    Assign,
    Plus,
}

// This function works, so I can access Token here
fn toto() -> Token {
  Token::Assign
}

#[cfg(test)]
mod tests {
  #[test]
  fn next_token() {
    let inputs = "=+";

    let expected_tokens = [Token::Assign, Token::Plus];
    // The error I get:    ^^^^^ use of undeclared type or module `Token`
  }
}

I expect this example to work, but it doesn't, and I get "use of undeclared type or module Token" for the two tokens of expected_token.

1 Answers

I am missing use super::*; in the mod tests, which imports names from the outer scope (here the file). Here's the corrected minimal example:

#[derive(PartialEq)]
enum Token {
    Assign,
    Plus,
}

fn toto() -> Token {
  Token::Assign
}

#[cfg(test)]
mod tests {
  use super::*;

  #[test]
  fn next_token() {
    let inputs = "=+";

    let expected_tokens = [Token::Assign, Token::Plus];
  }
}
Related