I use this data structure in a project:
#[derive(Serialize, Deserialize)]
pub enum Field {
last_name(String),
first_name(String),
/* etc. */
}
#[derive(Serialize, Deserialize)]
pub struct Update {
pub id: Id,
pub field: Field,
}
The enum is not really useful by itself, I use it for deserialization of JSON. So is it possible to do something like that?
#[derive(Serialize, Deserialize)]
pub struct PersonUpdate {
pub id: Id,
pub field: enum {
last_name(String),
first_name(String),
}
}
An enum in Rust is a type that represents data that is one of several possible variants. Each variant in the enum can optionally have data associated with it: #![allow(unused_variables)] fn main() { enum Message { Quit, ChangeColor(i32, i32, i32), Move { x: i32, y: i32 }, Write(String), }
Additionally, creating a function that can take any type of Machine as its parameter is not possible using structs; in such a case, enums must be used. With an enum, the type of machine can be identified inside the function by using pattern matching with the match keyword.
All variants of an enum use the same amount of memory (in case of your Foo type, 16 bytes, at least on my machine). The size of the enum's values is determined by its largest variant ( One , in your example). Therefore, the values can be stored in the array directly.
In Rust, methods cannot only be defined on structs, they can also be defined on tuples and enums, and even on built-in types like integers.
It is not possible, you must give it a name, like you did in the first example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With