Beginner with Rust: a thing it does better than ANSI C
In C enum defines a set of named options and associates integer values to them. I often use enums for labeling types of structs. For example:
QUIT,
MOVE,
WRITE,
CHANGECOLOR
} msgtype_t;
By default, the first label gets value 0 while its successor gets value <prev value +1> unless specified otherwise.
In Rust an enum label can have any valid Rust type, including scalar types, functions, and custom types.
Therefore in Rust it is possible to define the message type as follows:
enum msg_t {
Quit,
Move { x: i32, y: i32 },
Write(String),
ChangeColor(i32, i32, i32),
}
typedef enum {
QUIT,
MOVE,
WRITE,
CHANGECOLOR
} msg_type_t;
typedef struct move_msg_st {
int x;
int y;
} move_msg_t;
typedef struct write_msg_st {
char* msg_str;
} write_msg_t;
typedef struct change_color_msg_st {
int r;
int g;
int b;
} change_color_msg_t;
typedef union msg_data {
move_msg_t move_data;
write_msg_t write_data;
change_color_msg_t change_data;
} msg_data_t;
typedef struct msg_st {
msg_type_t msg_type;
msg_data_t msg_data;
} msg_t;
Comments
Post a Comment