【rCore OS 开源操作系统】Rust 练习题题解: Enums

news/2024/10/3 23:31:57 标签: rust, 操作系统, OS, 内存安全, 开源

OS_Rust__Enums_1">【rCore OS 开源操作系统】Rust 练习题题解: Enums

摘要

rCore OS 开源操作系统训练营学习中的代码练习部分。
在此记录下自己学习过程中的产物,以便于日后更有“收获感”。
后续还会继续完成其他章节的练习题题解。

正文

enums1

题目
rust">// enums1.rs
//
// No hints this time! ;)

// I AM NOT DONE

#[derive(Debug)]
enum Message {
    // TODO: define a few types of messages as used below
}

fn main() {
    println!("{:?}", Message::Quit);
    println!("{:?}", Message::Echo);
    println!("{:?}", Message::Move);
    println!("{:?}", Message::ChangeColor);
}
题解

目测就是基本的枚举值语法。
甚至简单到题目中出现了 No hints this time! ;),不会做那就有点汗颜了。

参考资料:https://doc.rust-lang.org/stable/book/ch06-01-defining-an-enum.html

rust">// enums1.rs
//
// No hints this time! ;)

#[derive(Debug)]
enum Message {
    // TODO: define a few types of messages as used below
}

fn main() {
    println!("{:?}", Message::Quit);
    println!("{:?}", Message::Echo);
    println!("{:?}", Message::Move);
    println!("{:?}", Message::ChangeColor);
}

enums2

这里的核心知识点是,枚举与数据类型关联。

题目
rust">// enums2.rs
//
// Execute `rustlings hint enums2` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE

#[derive(Debug)]
enum Message {
    // TODO: define the different variants used below
}

impl Message {
    fn call(&self) {
        println!("{:?}", self);
    }
}

fn main() {
    let messages = [
        Message::Move { x: 10, y: 30 },
        Message::Echo(String::from("hello world")),
        Message::ChangeColor(200, 255, 255),
        Message::Quit,
    ];

    for message in &messages {
        message.call();
    }
}

题解

题解与上面一样。

rust">// enums2.rs
//
// Execute `rustlings hint enums2` or use the `hint` watch subcommand for a
// hint.

#[derive(Debug)]
enum Message {
    // TODO: define the different variants used below
    Move { x: i32, y: i32 },
    Echo(String),
    ChangeColor(i32, i32, i32),
    Quit,
}

impl Message {
    fn call(&self) {
        println!("{:?}", self);
    }
}

fn main() {
    let messages = [
        Message::Move { x: 10, y: 30 },
        Message::Echo(String::from("hello world")),
        Message::ChangeColor(200, 255, 255),
        Message::Quit,
    ];

    for message in &messages {
        message.call();
    }
}

enums3

题目
rust">// enums3.rs
//
// Address all the TODOs to make the tests pass!
//
// Execute `rustlings hint enums3` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE

enum Message {
    // TODO: implement the message variant types based on their usage below
}

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

struct State {
    color: (u8, u8, u8),
    position: Point,
    quit: bool,
    message: String
}

impl State {
    fn change_color(&mut self, color: (u8, u8, u8)) {
        self.color = color;
    }

    fn quit(&mut self) {
        self.quit = true;
    }

    fn echo(&mut self, s: String) { self.message = s }

    fn move_position(&mut self, p: Point) {
        self.position = p;
    }

    fn process(&mut self, message: Message) {
        // TODO: create a match expression to process the different message
        // variants
        // Remember: When passing a tuple as a function argument, you'll need
        // extra parentheses: fn function((t, u, p, l, e))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_match_message_call() {
        let mut state = State {
            quit: false,
            position: Point { x: 0, y: 0 },
            color: (0, 0, 0),
            message: "hello world".to_string(),
        };
        state.process(Message::ChangeColor(255, 0, 255));
        state.process(Message::Echo(String::from("hello world")));
        state.process(Message::Move(Point { x: 10, y: 15 }));
        state.process(Message::Quit);

        assert_eq!(state.color, (255, 0, 255));
        assert_eq!(state.position.x, 10);
        assert_eq!(state.position.y, 15);
        assert_eq!(state.quit, true);
        assert_eq!(state.message, "hello world");
    }
}
题解

在要求会用枚举的基础上,结合了常常配合枚举一起使用的模式匹配

rust">// enums3.rs
//
// Address all the TODOs to make the tests pass!
//
// Execute `rustlings hint enums3` or use the `hint` watch subcommand for a
// hint.

enum Message {
    // TODO: implement the message variant types based on their usage below
    ChangeColor(u8, u8, u8),
    Echo(String),
    Move(Point),
    Quit,
}

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

struct State {
    color: (u8, u8, u8),
    position: Point,
    quit: bool,
    message: String,
}

impl State {
    fn change_color(&mut self, color: (u8, u8, u8)) {
        self.color = color;
    }

    fn quit(&mut self) {
        self.quit = true;
    }

    fn echo(&mut self, s: String) {
        self.message = s
    }

    fn move_position(&mut self, p: Point) {
        self.position = p;
    }

    fn process(&mut self, message: Message) {
        // TODO: create a match expression to process the different message
        // variants
        // Remember: When passing a tuple as a function argument, you'll need
        // extra parentheses: fn function((t, u, p, l, e))
        match message {
            Message::ChangeColor(r, g, b) => self.change_color((r, g, b)),
            Message::Echo(string) => self.echo(string),
            Message::Move(point) => self.move_position(point),
            Message::Quit => self.quit(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_match_message_call() {
        let mut state = State {
            quit: false,
            position: Point { x: 0, y: 0 },
            color: (0, 0, 0),
            message: "hello world".to_string(),
        };
        state.process(Message::ChangeColor(255, 0, 255));
        state.process(Message::Echo(String::from("hello world")));
        state.process(Message::Move(Point { x: 10, y: 15 }));
        state.process(Message::Quit);

        assert_eq!(state.color, (255, 0, 255));
        assert_eq!(state.position.x, 10);
        assert_eq!(state.position.y, 15);
        assert_eq!(state.quit, true);
        assert_eq!(state.message, "hello world");
    }
}


http://www.niftyadmin.cn/n/5689117.html

相关文章

Leetcode 275. H 指数 II

1.题目基本信息 1.1.题目描述 给你一个整数数组 citations ,其中 citations[i] 表示研究者的第 i 篇论文被引用的次数,citations 已经按照 升序排列 。计算并返回该研究者的 h 指数。 h 指数的定义:h 代表“高引用次数”(high …

MySQL基础篇 - 事务

01 事务的简介 【1】什么是事务:事务是一组操作集合,要么同时操作成功,要么同时操作失败。 【2】对于MySQL数据库来说默认一条SQL语句就是一个事务,且事务是默认自动提交的。 我们可以把多条SQL语句设置成一个事务,使…

微软准备了 Windows 11 24H2 ISO “OOBE/BypassNRO“命令依然可用

Windows 11 24H2 可能在未来几周内开始推出。 微软已经要求 OEM 遵循新的指南准备好 Windows 11 24H2 就绪的驱动程序,并且现在已经开始准备媒体文件 (.ISO)。 OEM ISO 的链接已在微软服务器上发布。 一个标有"X23-81971_26100.1742.240906-0331.ge_release_sv…

overleaf的使用[11]:使用和管理LaTeX模板

菜鸟:嗨,老鸟,我最近在使用Overleaf写论文,但总觉得每次都要从头开始,效率好低。你能告诉我有什么办法可以改善这个情况吗? 老鸟:当然可以,菜鸟!你有没有听说过在Overle…

CentOS 7 系统中安装与配置 Telnet 服务详解(使用root登录)

目录 前言1. 安装 Telnet 服务端2. 配置 Telnet 服务允许 root 用户登录3. 启动与管理 Telnet 服务4. 配置防火墙允许 Telnet 通信5. 注册 Telnet 服务6. 添加 pts/0 终端7. 重启 xinetd 服务8. 在 Windows 本地终端安装 Telnet 客户端结语 前言 Telnet 是一种网络协议&#x…

用网络分析仪测试功分器驻波的5个步骤

在射频系统中,功分器的驻波比直接关系到信号的稳定性和传输效率。本文将带您深入了解驻波比的测试方法和影响其结果的因素。 一、功分器驻波比 驻波(Voltage Standing Wave Ratio),简称SWR或VSWR,是指频率相同、传输方向相反的两种波&#xf…

stm32 bootloader跳转程序设计

文章目录 1、bootloader跳转程序设计&#xff08;1&#xff09;跳转程序&#xff08;2&#xff09;、app程序中需要注意<1>、在keil中ROM起始地址和分配的空间大小<2>、在system_stm32f4xx.c中设置VECT_TAB_OFFSET为需要偏移的地址<3>、main函数中使能中断 总…

(四)Mysql 数据库备份恢复全攻略

一、数据库备份 数据库备份目的和数据库故障类型 目的&#xff1a; 当发生故障时&#xff0c;将损失降到最低。保证能够快速从备份数据中恢复&#xff0c;确保数据稳定运行。故障类型&#xff1a; 程序错误&#xff1a;Mysql 服务器端程序故障无法使用。人为误操作&#xff1a;…