问题描述
我在一些示例代码中遇到了这个片段.它工作正常,但我收到一个 linter 错误,提示它应该被构造为 if-let 语句.
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 {
glutin::Event::WindowEvent { event, .. } => match event {
glutin::WindowEvent::Closed => return glutin::ControlFlow::Break,
glutin::WindowEvent::Resized(w, h) => gl_window.resize(w, h),
_ => (),
},
_ => ()
}
这是我对其进行重组的尝试:
This was my attempt to restructure it:
if let _ = glutin::Event::WindowEvent { event, .. } {
match event {
glutin::WindowEvent::Closed => return glutin::ControlFlow::Break,
glutin::WindowEvent::Resized(w, h) => gl_window.resize(w, h),
_ => (),
}
}
糟糕,这是一个语法错误.清除 linter 警告的正确方法是什么?
Oops, that's a syntax error. What would be the correct way to clear the linter warning?
更仔细地查看代码后,我意识到我不理解语法.glutin::Event::WindowEvent { event, .. }
看起来像创建 WindowEvent
的新实例的语法,但如何在 match 语句中允许它呢?
After looking at the code more closely, I realized that I don't understand the syntax. glutin::Event::WindowEvent { event, .. }
looks like the syntax for creating a new instance of WindowEvent
but how can that be allowed inside a match statement?
另外,..
是什么意思?我熟悉 ..Default::default()
,但不熟悉双点本身.
Also, what does the ..
mean? I'm familiar with ..Default::default()
, but not the double dot by itself.
推荐答案
逃避你的语法叫做 解构.
此模式允许匹配结构、枚举或元组中的某些字段.因此,您不能将 if let 与绑定右侧的解构一起使用.
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.
你想要的代码大概是:
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),
_ => (),
}
}
右侧的 event
变量与从模式中提取的变量之间可能存在混淆.在解构中使用 event
是强制性的,因为它需要按名称使用结构字段.
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.
这篇关于if-let 语句的语法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!