Enum variant never constructed


#1

why does this not compile?

// result1.rs
// Make this test pass! Scroll down for hints :)

#[derive(PartialEq,Debug)]
struct PositiveNonzeroInteger(u64);

#[derive(PartialEq,Debug)]
enum CreationError {
    Negative,
    Zero,
}

impl PositiveNonzeroInteger {
    fn new(value: i64) -> Result<PositiveNonzeroInteger, CreationError> {
        if value > 0 {
            Ok(PositiveNonzeroInteger(value as u64))
        } else if value < 0 {
            Err(CreationError::Negative)  //what's wrong?
        } else {
            Err(CreationError::Zero)
        }
    }
}

#[test]
fn test_creation() {
    assert!(PositiveNonzeroInteger::new(10).is_ok());
    assert_eq!(Err(CreationError::Negative), PositiveNonzeroInteger::new(-10));
    assert_eq!(Err(CreationError::Zero), PositiveNonzeroInteger::new(0));
}

#2

It does compile and will run the test, it just also emits warnings because new is never used and is private (same with test_creation), so it can see that anything used in new is also not used. Then it sees that CreationError is private, and sees that it isn’t created anywhere else so it emits the warning that it isn’t used.

Next time you post a question with code, please also post a playground link like so:
playground


#3

Ok, I was confused. Now I know #[test] by itself sets a privacy boundry as well.

Thank you for the answer and the tip.