C enumeration like Rust data type c-like enum

Table of contents

enumeration type enum

Definitions and declarations

Example 1: Color enumeration

Example 2: Direction enumeration

Example 3: Weekday enumeration

class C enum C-like

printout

coerce to integer

Example 1: Weekday enumeration

Example 2: HttpStatus enumeration

Example 3: Color enumeration

pattern matching

match expression

enumeration method


enumeration type enum

An enumerated type is a type used to represent a finite set of interrelated discrete data. These values ​​can be different integers, strings, or other types of objects. The elements in the enumeration body are called "members". In the rust language, the members in the enumeration can be regarded as structures . Of course, an enumeration can nest another enumeration.

Definitions and declarations

In Rust, enumerated types can be defined with the keyword enum :

enum MyEnum {
    Variant1,
    Variant2,
    Variant3,
    //...
    VariantN,
}

enum is an acronym for enumerate/enumeration, and MyEnum is a custom enumeration name .

Variant means variable, and some translate it as "variant". I think it is more appropriate to use the name " member " in C/C++ language .

The number N of Variant must be limited, too many variables are meaningless; and N>=2, no member or a single member is meaningless.

By using enumerated types, a limited set of values ​​can be defined for different situations. This is useful in situations where multiple possible states or options need to be represented. The following are several classic examples of common enumerated types:

Example 1: Color enumeration

The Color enumeration represents the different possible values ​​of a color, such as red, green, and blue.

enum Color {
    Red,
    Green,
    Blue,
}

Example 2: Direction enumeration

The Direction enum represents the different possible values ​​for a direction, such as up, down, left, and right.

enum Direction {
    Up,
    Down,
    Left,
    Right,
}

Example 3: Weekday enumeration

The Weekday enumeration represents different days of the week, such as an enumeration of 7 days in a week.

enum Weekday {
    Sunday,
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,    
}

class C enum C-like

The enumeration members in the C/C++ language are only allowed to be usigned int constants, also known as enumeration constants. If there is a C-style enumeration in Rust, it must be satisfied that the members in the enumeration are all unit structures .

printout

Use #[derive(Debug)] to simplify output, format: println!("{ :? }", MyEnum :: VariantN); 

#[derive(Debug)]
enum Number {
    Zero,
    One,
    Two,
    Three,
}

fn main() {
    println!("zero is {:?}", Number::Zero);
    println!("one is {:?}", Number::One);
    println!("Two is {:?}", Number::Two);
    println!("Three is {:?}", Number::Three);
}

output:

zero is Zero
one is One
Two is Two
Three is Three

coerce to integer

Do not use #[derive(Debug)], force it to be converted to an integer and output

enum Number {
    Zero,
    One,
    Two,
    Three,
}

fn main() {
    println!("zero is {}", Number::Zero as i32);
    println!("one is {}", Number::One as i32);
    println!("Two is {}", Number::Two as i32);
    println!("Three is {}", Number::Three as i32);
}

output:

zero is 0
one is 1
Two is 2
Three is 3

C-like enumerations can also be converted into a set of discrete integers by assignment:

#![allow(dead_code)]

#[derive(Debug)]
enum Number {
    Zero,
    One,
    Two,
    Five = 5,
    Six,
}

fn main() {
    println!("zero is {}", Number::Zero as i32);
    println!("one is {}", Number::One as i32);
    println!("Five is {}", Number::Five as i32);
    println!("Six is {}", Number::Six as i32);
}

output:

0
1
5

Note: The enumeration member Two has not been called in the whole program, you can use #![allow(dead_code)] to filter out warnings. Without this line, the above program can output results during compilation and execution, but at the same time warn: warning: variant `Two` is never constructed.

Example 1: Weekday enumeration

The Weekday enumeration assigns values ​​so that Monday to Sunday correspond to integers 1~7; rather than the default Sunday to Saturday corresponding to integers 0~6.

#![allow(dead_code)]

enum Weekday {
    Sunday = 7,
    Monday = 1,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
}

fn main() {
    println!("Sunday is {}", Weekday::Sunday as i32);
    println!("Tuesday is {}", Weekday::Tuesday as i32);
    println!("Saturday is {}", Weekday::Saturday as i32);
}

output:

Sunday is 7
Tuesday is 2
Saturday is 6 

Example 2: HttpStatus enumeration

The HttpStatus enumeration indicates different HTTP status codes. For example, 200 indicates success, 404 indicates that the page cannot be found, and 500 indicates an internal server error, etc. There are nearly a hundred members in total, and the enumeration is as follows:

#![allow(dead_code)]

 enum HttpStatus {
    Continue = 100, //"CONTINUE" 继续
    SwitchingProtocols, //"SWITCHING_PROTOCOLS" 切换协议
    Processing, //"PROCESSING" 执行
    Checkpoint, //"CHECKPOINT" 检查点
    OK = 200, //"OK" OK
    CREATED, //"Created" 创建
    ACCEPTED, //"Accepted" 接受
    NonAuthoritativeInformation, //"NON_AUTHORITATIVE_INFORMATION" 非权威信息
    NoContent, //"NO_CONTENT" 没有内容
    ResetContent, //"RESET_CONTENT" 重置内容
    PartialContent, //"PARTIAL_CONTENT" 部分内容
    MultiStatus, //"MULTI_STATUS" 多个状态
    AlreadyReported, //"ALREADY_REPORTED" 已发
    IMUsed = 226, //"IM_USED" 已过时
    MultipleChoices = 300, //"MULTIPLE_CHOICES" 多选择
    MovedPermanently, //"MOVED_PERMANENTLY" 永久移动
    FOUND, //"Found" 找到
    MovedTemporarily, //"MOVED_TEMPORARILY"
    SeeOther, //"SEE_OTHER" 参见其它
    NotModified, //"NOT_MODIFIED" 未修改
    UseProxy, //"USE_PROXY"),
    TemporaryRedirect, //"TEMPORARY_REDIRECT" 暂时重定向
    PermanentRedirect, //"PERMANENT_REDIRECT" 永久重定向
    //......
    BadRequest = 400, //"BAD_REQUEST" 错误请求
    Unauthorized, //"UNAUTHORIZED" 未经授权
    PaymentRequired, //"PAYMENT_REQUIRED" 付费请求
    Forbidden, //"FORBIDDEN" 禁止
    NotFound, //"NOT_FOUND" 未找到
    MethodNotAllowed, //"METHOD_NOT_ALLOWED" 方法不容许
    NotAcceptable, //"NOT_ACCEPTABLE" 方法不接受
    //......
    InternalServerError = 500, // "INTERNAL_SERVER_ERROR" 服务器遇到了意料不到的情况,不能完成客户的请求
    NotImplemented, //"NOT_IMPLEMENTED"  服务器不支持实现请求所需要的功能
    BadGateway, //"BAD_GATEWAY" 从上游服务器接收到无效的响应
    ServiceUnavailable, //"SERVICE_UNAVAILABLE" 服务不可用
    GatewayTimeout, //"GATEWAY_TIMEOUT") 网关不能及时地从远程服务器获得应答
    //......
}

fn main() {
    println!("OK is {}", HttpStatus::OK as i32);
    println!("Bad Request is {}", HttpStatus::BadRequest as i32);
}

output:

OK is 200
Bad Request is 400

Example 3: Color enumeration

Use {:06x} format to output the color represented by 6-digit hexadecimal number

enum Color {
    Red = 0xff0000,
    Green = 0x00ff00,
    Blue = 0x0000ff,
}

fn main() {
    println!("roses are #{:06x}", Color::Red as i32);
    println!("leaves are #{:06x}", Color::Green as i32);
    println!("violets are #{:06x}", Color::Blue as i32);
    println!("red is {}", Color::Red as i32);
    println!("green is {}", Color::Green as i32);
    println!("blue is {}", Color::Blue as i32);
}

output:

roses are #ff0000
leaves are #00ff00
violets are #0000ff
red is 16711680
green is 65280
blue is 255 

pattern matching

Enum types are often used in Rust in conjunction with pattern matching to perform different operations based on the value of the enum type.

match expression

The match expression can be used to pattern match enum variants and execute the corresponding code block according to the matched variant. Its syntax is as follows:

match value {
    pattern1 => {
        // 如果 value 匹配了 pattern1
    },
    pattern2 => {
        // 如果 value 匹配了 pattern2
    },
    // 其他模式...
}

For example, define an enumeration type named Color, which contains three members: Red, Green and Blue. Each member is a legal identifier used to represent a different color.

enum Color {
    Red,
    Green,
    Blue,
}

For the above Color enumeration types, you can use pattern matching to perform corresponding operations:

fn print_color(color: Color) {
    match color {
        Color::Red => println!("The color is Red"),
        Color::Green => println!("The color is Green"),
        Color::Blue => println!("The color is Blue"),
    }
}

In the above example, the function print_color receives a parameter of type Color and uses match for pattern matching. According to the color value passed in, the corresponding operation will be performed.

enumeration method

You can also customize the method to define the corresponding value for each member.

#![allow(dead_code)]

enum Color {
    Red,
    Green,
    Blue,
    Yellow,
    Magenta,
    Cyan,
}

impl Color {
    fn to_rgb(&self) -> (u8, u8, u8) {
        match self {
            Color::Red => (255, 0, 0),
            Color::Green => (0, 255, 0),
            Color::Blue => (0, 0, 255),
            Color::Yellow => (255, 255, 0),
            Color::Magenta => (255, 0, 255),
            Color::Cyan => (0, 255, 255),
        }
    }
}
  
fn main() {
    let red = Color::Red;
    let red_rgb = red.to_rgb();
    println!("RGB value of red: {:?}", red_rgb);
    
    let yellow = Color::Yellow;
    let yellow_rgb = yellow.to_rgb();
    println!("RGB value of yellow: {:?}", yellow_rgb);
}

In the above example, we implemented a to_rgb method for the Color enum type to convert the color to an RGB value.

To sum up, Rust's enumeration type provides a powerful pattern matching function, making the enumeration type very flexible and reliable, suitable for various scenarios and data processing requirements. This article only initially learns the C-like enumeration types, and other classifications will be decomposed in the next chapter.

Guess you like

Origin blog.csdn.net/boysoft2002/article/details/131774598