当前位置: 首页 > article >正文

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

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

摘要

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

正文

enums1

题目
// 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

// 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

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

题目
// 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();
    }
}

题解

题解与上面一样。

// 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

题目
// 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");
    }
}
题解

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

// 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.kler.cn/news/330162.html

相关文章:

  • Nacos 是阿里巴巴开源的一款动态服务发现、配置管理和服务管理平台,旨在帮助开发者更轻松地构建、部署和管理微服务应用。
  • python单例和工厂模式
  • OpenCV库 详细常见操作
  • Lumerical脚本语言-系统(System)
  • RAG(检索增强生成)新探索:IdentityRAG 提高 RAG 准确性
  • springboot儿童物品共享平台的设计与实现
  • VMware Aria Suite Lifecycle 8.18 发布,新增功能概览
  • Go基础学习10-原子并发包sync.atomic的使用:CSA、Swap、atomic.Value......
  • 基于单片机的两轮直立平衡车的设计
  • 经验笔记:JavaScript 中的对象
  • 阿里云部署1Panel(失败版)
  • setState是同步更新还是异步更新
  • 基于Python的人工智能应用案例系列(18):SpaCy简历信息抽取
  • 旅游避坑指南
  • 基础岛第6关:OpenCompass 评测 InternLM-1.8B 实践
  • 深入了解 Ne10:优化 ARM 处理器的数字信号处理库
  • [C++][第三方库][gflags]详细讲解
  • Vue项目开发注意事项
  • Ubuntu22.04之测试本机网口速度(二百七十二)
  • PySpark把一列数据上下移动,时序数据
  • 【趣学Python算法100例】三色球
  • 认知杂谈94《菜鸟的自我修炼:创业的那些事》
  • 两数相加leetcode
  • 样式重置 normalize.css
  • 【零基础入门产品经理】学习准备篇 | 需要学一些什么呢?
  • 死锁的成因与解决方案
  • 景联文科技入选《2024中国AI大模型产业图谱2.0版》数据集代表厂商
  • Vue3.0面试题汇总
  • 如何实现一个Mini Spring Boot
  • Leecode热题100-283.移动零