代码之家  ›  专栏  ›  技术社区  ›  unsafe_where_true

在测试中匹配单个枚举变量,对其他匹配不感兴趣

  •  -1
  • unsafe_where_true  · 技术社区  · 11 月前
    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;
    }
    

    我知道编译器在 test_locker 并非所有匹配都已解决。

    但我没能确定如何解决这个问题。事实上,在这次测试中,我知道它只能是那种状态,所以我实际上不需要匹配。

    我尝试了几件事:

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

    我原以为这会失败,因为 ids 在第一行中已经键入为 State::Started .

    还试图通过宣布 let ids:Vec<Id> 以前,但那似乎是在某种不同的范围内,因为那时我做不到 let State::Started(ids) = ...

    我想我可以先做一场比赛,忽略所有其他选择,但我觉得应该有一种更优雅的方式?

    1 回复  |  直到 11 月前
        1
  •  0
  •   kmdreko    11 月前

    使用 let-else 语法:

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