gpt4 book ai didi

enums - 如何同时破坏枚举的字段和整体值?

转载 作者:行者123 更新时间:2023-12-03 11:41:37 27 4
gpt4 key购买 nike

我想匹配一个枚举变量,对其进行处理,然后将其进一步传递。该代码应如下所示:

enum Event {
WindowEvent {
event: WindowEvent,
window_id: usize,
},
}
enum WindowEvent {
Resized(u8),
}

struct Demo {
size: u8,
}

impl Demo {
fn reproduction(&mut self, event: Event) {
match event {
e
@
Event::WindowEvent {
event: WindowEvent::Resized(size),
..
} => {
self.size = size;
self.handle_event(e);
}
}
}

fn handle_event(&self, _event: Event) {}
}
此代码未通过借阅检查器:
error[E0007]: cannot bind by-move with sub-bindings
--> src/lib.rs:18:13
|
18 | / e
19 | | @
20 | | Event::WindowEvent {
21 | | event: WindowEvent::Resized(size),
22 | | ..
23 | | } => {
| |_____________^ binds an already bound by-move value by moving it

error[E0658]: pattern bindings after an `@` are unstable
--> src/lib.rs:21:45
|
21 | event: WindowEvent::Resized(size),
| ^^^^
|
= note: see issue #65490 <https://github.com/rust-lang/rust/issues/65490> for more information

error[E0382]: use of moved value: `event`
--> src/lib.rs:21:45
|
16 | fn reproduction(&mut self, event: Event) {
| ----- move occurs because `event` has type `Event`, which does not implement the `Copy` trait
17 | match event {
18 | / e
19 | | @
20 | | Event::WindowEvent {
21 | | event: WindowEvent::Resized(size),
| | ^^^^ value used here after move
22 | | ..
23 | | } => {
| |_____________- value moved here
我可以完全分解 event并在传递给 handle_event时再次构造它,但这似乎是错误的。当可以传递现有对象时,为什么要构造一个新对象?当我可以使用通配符 ..时,为什么还要关心其他字段(可能有很多!):
match event {
Event::WindowEvent {
event: WindowEvent::Resized(size),
window_id,
} => {
self.size = size;
self.handle_event(Event::WindowEvent {
event: WindowEvent::Resized(size),
window_id,
});
}
}
我发现了另一个需要两次匹配的解决方案:
match event {
e
@
Event::WindowEvent {
event: WindowEvent::Resized(_),
..
} => {
if let Event::WindowEvent {
event: WindowEvent::Resized(size),
..
} = e
{
self.size = size;
}
self.handle_event(e);
}
}
有没有更好的方法来构造枚举变量而不丢失原始值?

最佳答案

在这种情况下,可以重用event值,而无需尝试使用精美的模式匹配技术:

match event {
Event::WindowEvent {
event: WindowEvent::Resized(size),
..
} => {
self.size = size;
self.handle_event(event);
}
}

将来会有另一种选择。由于编译器的错误消息状态为:

error[E0007]: cannot bind by-move with sub-bindings

error[E0658]: pattern bindings after an @ are unstable

note: see issue #65490 for more information


在每晚的Rust上,您可以添加 #![feature(bindings_after_at)],然后更改您的代码以与引用匹配:
fn reproduction(&mut self, event: Event) {
match &event {
e
@
Event::WindowEvent {
event: WindowEvent::Resized(size),
..
} => {
self.size = *size;
self.handle_event(e);
}
}
}

fn handle_event(&self, _event: &Event) {}
如果要匹配的枚举是 Copy,则不需要引用。

关于enums - 如何同时破坏枚举的字段和整体值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64034703/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com