【rCore OS 开源利用系统】Rust 枚举与模式匹配

打印 上一主题 下一主题

主题 1781|帖子 1781|积分 5343

【rCore OS 开源利用系统】Rust 枚举与模式匹配

前言

现在固然人在大阪,但是还是把笔记本是从来都带身上的。
每天玩了之后,晚上还可以学一学rust写写代码。

言归正传,本章节涉及到的知识点有:


  • 枚举的应用:这里不再是基本语法,而是要学会用。
  • 模式匹配实战:利用 match来处理题目。
  • 语法糖:利用where let和if let来处理简化代码。
  • 引用与借用:复习一下。
知识点

训练题

option1

标题

  1. // options1.rs
  2. //
  3. // Execute `rustlings hint options1` or use the `hint` watch subcommand for a
  4. // hint.
  5. // I AM NOT DONE
  6. // This function returns how much icecream there is left in the fridge.
  7. // If it's before 10PM, there's 5 pieces left. At 10PM, someone eats them
  8. // all, so there'll be no more left :(
  9. fn maybe_icecream(time_of_day: u16) -> Option<u16> {
  10.     // We use the 24-hour system here, so 10PM is a value of 22 and 12AM is a
  11.     // value of 0 The Option output should gracefully handle cases where
  12.     // time_of_day > 23.
  13.     // TODO: Complete the function body - remember to return an Option!
  14.     ???
  15. }
  16. #[cfg(test)]
  17. mod tests {
  18.     use super::*;
  19.     #[test]
  20.     fn check_icecream() {
  21.         assert_eq!(maybe_icecream(9), Some(5));
  22.         assert_eq!(maybe_icecream(10), Some(5));
  23.         assert_eq!(maybe_icecream(23), Some(0));
  24.         assert_eq!(maybe_icecream(22), Some(0));
  25.         assert_eq!(maybe_icecream(25), None);
  26.     }
  27.     #[test]
  28.     fn raw_value() {
  29.         // TODO: Fix this test. How do you get at the value contained in the
  30.         // Option?
  31.         let icecreams = maybe_icecream(12);
  32.         assert_eq!(icecreams, 5);
  33.     }
  34. }
复制代码
题解

没有特别难的点,主要是搞懂标题的意思:
   22 点之前,冰箱里都有 5 个冰淇淋

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

南飓风

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表