简体   繁体   English

从结构中创建枚举

[英]Make an Enum from struct

I want to make an enum from a struct.我想从结构中创建一个枚举。

The definitions:定义:

struct Point {
    x: u8,
    y: u8,
}

enum Message {
    Move { x: u8, y: u8 },
    nothing,
}

So if I have instantiated a Point in my code, how can I make a Message from the struct?因此,如果我在我的代码中实例化了一个Point ,我该如何从结构中创建一个Message

I've tried this code:我试过这段代码:

Message::Move(Point { x: 10, y: 15 })

But this code throws an error saying但是这段代码抛出一个错误说

error[E0423]: expected function, tuple struct or tuple variant, found struct variant `Message::Move`

Your enum variant can simply contain an instance of the struct.您的枚举变体可以只包含该结构的一个实例。

enum Message {
  Move(Point),
  NoMessage,
}

Then the syntax you wanted will work as-is.然后你想要的语法将按原样工作。

Message::Move(Point { x: 10, y: 15 })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM