rustenumsmatchdeconstructor

Matching a single enum variant in a test, not interested in other other matches


pub enum State {
   Started(Vec<Id>),
   InProgress,
   Terminated
}

pub trait Locker {
  async fn start(&mut self, id: Id) -> State; 
}

#[tokio::test]
async fn test_locker() {
   let State::Started(ids) = locker.start().await;
}

I understand that the compiler complains in test_locker that not all matches have been addressed.

But I failed to identify how to fix that. In fact, in this test, I know it can only be that state, so I don't actually need a match.

I tried several things:

let State::Started(ids) = locker.start().await;
assert!(matches!(ids, State::Started(ids)));

I was expecting this to fail, as the ids in the first line are already typed to be of State::Started.

Also tried by declaring let ids:Vec<Id> before, but that appears to then be in some kind of different scope, as I can't then do let State::Started(ids) = ...

I guess I could just do a match first and ignore all the other options, but I feel there should be a more elegant way?


Solution

  • Use the let-else syntax:

    let State::Started(ids) = locker.start().await else { panic!("not started") };