What is the syntax for an if-let statement?

后端 未结 2 1246
难免孤独
难免孤独 2021-01-28 02:46

I encountered this snippet in some example code. It works fine, but I got a linter error saying that it should be structured as an if-let statement.

match event         


        
2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-28 03:45

    The syntax that eludes you is called destructuring.

    This pattern allows to match certain fields in a struct, enum, or tuple. You therefore cannot just use if let with the destructuring on the right side of the binding.

    The code you want is probably:

    if let glutin::Event::WindowEvent { event, .. } = event {
      match event {
          glutin::WindowEvent::Closed => return glutin::ControlFlow::Break,
          glutin::WindowEvent::Resized(w, h) => gl_window.resize(w, h),
          _ => (),
      }
    }
    

    There is a possible confusion between the right hand event variable and the one extracted from the pattern. The use of event in the destructuring is made mandatory because it needs to use struct fields by name.

提交回复
热议问题