Rust学习笔记_13——枚举

发布于:2024-12-18 ⋅ 阅读:(317) ⋅ 点赞:(0)

Rust学习笔记_10——守卫
Rust学习笔记_11——函数
Rust学习笔记_12——闭包


枚举


在Rust编程语言中,枚举(enum)是一种非常有用的数据类型,允许你定义一个变量的集合,这个变量的值可以是多个不同的类型之一。

1. 定义

枚举通过enum关键字定义。每个枚举成员(也称为变体)可以是无值的,也可以包含值

1.1 无值变体

Direction枚举有四个无值变体:NorthEastSouthWest

enum Direction {
    North,
    East,
    South,
    West,
}
1.2 有值变体

IpAddrKind枚举有两个有值变体:V4V6V4包含四个u8类型的值,而V6包含一个String类型的值。

enum IpAddrKind {
    V4(u8, u8, u8, u8),
    V6(String),
}
1.3 枚举与泛型的结合

Rust中的枚举还可以与泛型结合使用,从而创建更加通用和灵活的数据类型。

enum ErrorLevel<T> {
    Error(T),
    Info(T),
    Warning(T),
}

2. 使用

2.1 和匹配模式一起使用

通过匹配(match)表达式检查枚举变量的值,并根据不同的变体执行不同的代码

fn main() {
    let some_number = IpAddrKind::V4(192, 168, 1, 1);

    match some_number {
        IpAddrKind::V4(a, b, c, d) => {
            println!("IPv4 address: {}.{}.{}.{}", a, b, c, d);
        }
        IpAddrKind::V6(s) => {
            println!("IPv6 address: {}", s);
        }
    }
}
2.2 枚举作为类型别名
enum Message {
    Quit,
    Move { x: i32, y: i32 },
    Write(String),
    ChangeColor(i32, i32, i32),
}

fn main() {
    let msg = Message::Write(String::from("hello"));

    match msg {
        Message::Quit => {
            println!("Quit");
        }
        Message::Move { x, y } => {
            println!("Move to x={}, y={}", x, y);
        }
        Message::Write(text) => {
            println!("Write: {}", text);
        }
        Message::ChangeColor(r, g, b) => {
            println!("Change color to ({}, {}, {})", r, g, b);
        }
    }
}

3. 常用枚举类型

Rust中有两个广泛使用的枚举类型:OptionResult

  1. Option:用于表示可能不存在的值。它有两个成员:Some(T)表示有值的情况,None表示没有值的情况。Option类型在Rust中非常重要,因为它被用来替代其他语言中的空类型(如null、nil等),从而避免空指针异常等问题。
let some_number: Option<i32> = Some(5);
let no_number: Option<i32> = None;

match some_number {
    Some(x) => println!("Got a number: {}", x),
    None => println!("No number here!"),
}
  1. Result:用于表示一个操作的结果可能是成功也可能是错误。它有两个成员:Ok(T)表示成功的情况,Err(E)表示错误的情况。Result类型在Rust的错误处理中非常有用。
use std::fs::File;
use std::io::ErrorKind;

fn main() {
    let file = File::open("hello.txt");

    let result = match file {
        Ok(f) => {
            let metadata = f.metadata();
            if metadata.is_ok() {
                println!("File found!");
            } else {
                println!("Error reading metadata");
            }
            "Success"
        }
        Err(e) => {
            if e.kind() == ErrorKind::NotFound {
                println!("File not found!");
            } else {
                println!("Some other error: {}", e);
            }
            "Error"
        }
    };

    println!("Result: {}", result);
}

网站公告

今日签到

点亮在社区的每一天
去签到