gpt4 book ai didi

enums - 我如何构造/解构枚举的枚举?

转载 作者:行者123 更新时间:2023-11-29 08:22:44 24 4
gpt4 key购买 nike

我在匹配枚举的枚举时遇到了问题。结构类似于这样:

enum WebEvent {
PageLoad,
PageUnload,
KeyPress(char),
Paste(String),
Click { x: i64, y: i64 },
}
enum KeyEvent {
UpPressed,
DownPressed,
}

enum Event {
WebEvent,
KeyEvent,
}

fn inspect(event: Event) {
match event {
Event::WebEvent::PageLoad => println!("page loaded"),
Event::WebEvent::PageUnload => println!("page unloaded"),
Event::WebEvent::KeyPress(c) => println!("pressed '{}'.", c),
Event::WebEvent::Paste(s) => println!("pasted \"{}\".", s),
Event::WebEvent::Click { x, y } => {
println!("clicked at x={}, y={}.", x, y);
}
Event::KeyEvent => {
println!("got a key event");
}
}
}

fn main() {
let pressed = WebEvent::KeyPress('x');
inspect(pressed);
}

playground

这是我从编译器得到的错误:

error[E0433]: failed to resolve. Not a module `WebEvent`
--> src/main.rs:20:16
|
20 | Event::WebEvent::PageLoad => println!("page loaded"),
| ^^^^^^^^ Not a module `WebEvent`

error[E0433]: failed to resolve. Not a module `WebEvent`
--> src/main.rs:21:16
|
21 | Event::WebEvent::PageUnload => println!("page unloaded"),
| ^^^^^^^^ Not a module `WebEvent`

error[E0433]: failed to resolve. Not a module `WebEvent`
--> src/main.rs:22:16
|
22 | Event::WebEvent::KeyPress(c) => println!("pressed '{}'.", c),
| ^^^^^^^^ Not a module `WebEvent`

error[E0433]: failed to resolve. Not a module `WebEvent`
--> src/main.rs:23:16
|
23 | Event::WebEvent::Paste(s) => println!("pasted \"{}\".", s),
| ^^^^^^^^ Not a module `WebEvent`

error[E0433]: failed to resolve. Not a module `WebEvent`
--> src/main.rs:24:16
|
24 | Event::WebEvent::Click { x, y } => {
| ^^^^^^^^ Not a module `WebEvent`

error[E0308]: mismatched types
--> src/main.rs:35:13
|
35 | inspect(pressed);
| ^^^^^^^ expected enum `Event`, found enum `WebEvent`
|
= note: expected type `Event`
found type `WebEvent`

构造/解构枚举枚举的正确方法是什么?有什么办法可以做到这一点?

最佳答案

您忘记了枚举变体不是类型 - 您需要引入包装器以使枚举能够包含其他枚举:

enum Event {
WebEvent(WebEvent),
KeyEvent(KeyEvent)
}

剩下的就很简单了:

enum WebEvent {
PageLoad,
PageUnload,
KeyPress(char),
Paste(String),
Click { x: i64, y: i64 },
}

enum KeyEvent {
UpPressed,
DownPressed,
}

enum Event {
WebEvent(WebEvent),
KeyEvent(KeyEvent)
}

fn inspect(event: Event) {
if let Event::WebEvent(webevt) = event {
match webevt {
WebEvent::PageLoad => println!("page loaded"),
WebEvent::PageUnload => println!("page unloaded"),
WebEvent::KeyPress(c) => println!("pressed '{}'.", c),
WebEvent::Paste(s) => println!("pasted \"{}\".", s),
WebEvent::Click { x, y } => println!("clicked at x={}, y={}.", x, y)
}
} else {
println!("got a key event")
}
}

fn main() {
let pressed = Event::WebEvent(WebEvent::KeyPress('x')); // note the extra wrap here
inspect(pressed);
}

关于enums - 我如何构造/解构枚举的枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51188460/

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