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

devtools/2024/10/9 5:25:36/

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

摘要

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

正文

structs1

题目
rust">// structs1.rs
//
// Address all the TODOs to make the tests pass!
//
// Execute `rustlings hint structs1` or use the `hint` watch subcommand for a
// hint.// I AM NOT DONEstruct ColorClassicStruct {// TODO: Something goes here
}struct ColorTupleStruct(/* TODO: Something goes here */
);#[derive(Debug)]
struct UnitLikeStruct;#[cfg(test)]
mod tests {use super::*;#[test]fn classic_c_structs() {// TODO: Instantiate a classic c struct!// let green =assert_eq!(green.red, 0);assert_eq!(green.green, 255);assert_eq!(green.blue, 0);}#[test]fn tuple_structs() {// TODO: Instantiate a tuple struct!// let green =assert_eq!(green.0, 0);assert_eq!(green.1, 255);assert_eq!(green.2, 0);}#[test]fn unit_structs() {// TODO: Instantiate a unit-like struct!// let unit_like_struct =let message = format!("{:?}s are fun!", unit_like_struct);assert_eq!(message, "UnitLikeStructs are fun!");}
}
题解

参考《定义和举例说明结构体 - Rust 程序设计语言 中文版》第五章

structs 的基本如下:

rust">// 定义
struct User {age: i32,active: bool,username: String,email: String,sign_in_count: u64,
}
// 实现方法
impl User{fn info(&self) -> i32 {&self.age + 1 // 不加分号,就是 tail exp, 自带 return}
}
// 实例化
let rect1 = Rectangle {width: 30,height: 50,
};rect1.area()// 元组结构体定义struct User2(i32, i32, i32);let user = User2(1, 1, 1);// 类单元结构体定义struct User3;let user3 = User3;

所以答案也就是呼之欲出了:

rust">// structs1.rs
//
// Address all the TODOs to make the tests pass!
//
// Execute `rustlings hint structs1` or use the `hint` watch subcommand for a
// hint.struct ColorClassicStruct {// TODO: Something goes herered: i32,green: i32,blue: i32,
}struct ColorTupleStruct(/* TODO: Something goes here */ i32, i32, i32);#[derive(Debug)]
struct UnitLikeStruct;#[cfg(test)]
mod tests {use super::*;#[test]fn classic_c_structs() {// TODO: Instantiate a classic c struct!let green = ColorClassicStruct {red: 0,green: 255,blue: 0,};assert_eq!(green.red, 0);assert_eq!(green.green, 255);assert_eq!(green.blue, 0);}#[test]fn tuple_structs() {// TODO: Instantiate a tuple struct!let green = ColorTupleStruct(0, 255, 0);assert_eq!(green.0, 0);assert_eq!(green.1, 255);assert_eq!(green.2, 0);}#[test]fn unit_structs() {// TODO: Instantiate a unit-like struct!let unit_like_struct = UnitLikeStruct;let message = format!("{:?}s are fun!", unit_like_struct);assert_eq!(message, "UnitLikeStructs are fun!");}
}

Structs2

题目
rust">// structs2.rs
//
// Address all the TODOs to make the tests pass!
//
// Execute `rustlings hint structs2` or use the `hint` watch subcommand for a
// hint.// I AM NOT DONE#[derive(Debug)]
struct Order {name: String,year: u32,made_by_phone: bool,made_by_mobile: bool,made_by_email: bool,item_number: u32,count: u32,
}fn create_order_template() -> Order {Order {name: String::from("Bob"),year: 2019,made_by_phone: false,made_by_mobile: false,made_by_email: true,item_number: 123,count: 0,}
}#[cfg(test)]
mod tests {use super::*;#[test]fn your_order() {let order_template = create_order_template();// TODO: Create your own order using the update syntax and template above!// let your_order =assert_eq!(your_order.name, "Hacker in Rust");assert_eq!(your_order.year, order_template.year);assert_eq!(your_order.made_by_phone, order_template.made_by_phone);assert_eq!(your_order.made_by_mobile, order_template.made_by_mobile);assert_eq!(your_order.made_by_email, order_template.made_by_email);assert_eq!(your_order.item_number, order_template.item_number);assert_eq!(your_order.count, 1);}
}
解析

第二章节主要是考察结构体方法的实现。
参考:https://doc.rust-lang.org/stable/book/ch05-01-defining-structs.html#creating-instances-from-other-instances-with-struct-update-syntax

这里提到的update语法,是类似 JS 中的对象展开+字段覆盖的操作。

但是这里的覆盖是有固定优先级的,和字段书写顺序无关

rust">// structs2.rs
//
// Address all the TODOs to make the tests pass!
//
// Execute `rustlings hint structs2` or use the `hint` watch subcommand for a
// hint.#[derive(Debug)]
struct Order {name: String,year: u32,made_by_phone: bool,made_by_mobile: bool,made_by_email: bool,item_number: u32,count: u32,
}fn create_order_template() -> Order {Order {name: String::from("Bob"),year: 2019,made_by_phone: false,made_by_mobile: false,made_by_email: true,item_number: 123,count: 0,}
}#[cfg(test)]
mod tests {use super::*;#[test]fn your_order() {let order_template = create_order_template();// TODO: Create your own order using the update syntax and template above!let your_order = Order {name: String::from("Hacker in Rust"),count: 1,..order_template};assert_eq!(your_order.name, "Hacker in Rust");assert_eq!(your_order.year, order_template.year);assert_eq!(your_order.made_by_phone, order_template.made_by_phone);assert_eq!(your_order.made_by_mobile, order_template.made_by_mobile);assert_eq!(your_order.made_by_email, order_template.made_by_email);assert_eq!(your_order.item_number, order_template.item_number);assert_eq!(your_order.count, 1);}
}

Structs3

题目
rust">// structs3.rs
//
// Structs contain data, but can also have logic. In this exercise we have
// defined the Package struct and we want to test some logic attached to it.
// Make the code compile and the tests pass!
//
// Execute `rustlings hint structs3` or use the `hint` watch subcommand for a
// hint.// I AM NOT DONE#[derive(Debug)]
struct Package {sender_country: String,recipient_country: String,weight_in_grams: i32,
}impl Package {fn new(sender_country: String, recipient_country: String, weight_in_grams: i32) -> Package {if weight_in_grams <= 0 {panic!("Can not ship a weightless package.")} else {Package {sender_country,recipient_country,weight_in_grams,}}}fn is_international(&self) -> ??? {// Something goes here...}fn get_fees(&self, cents_per_gram: i32) -> ??? {// Something goes here...}
}#[cfg(test)]
mod tests {use super::*;#[test]#[should_panic]fn fail_creating_weightless_package() {let sender_country = String::from("Spain");let recipient_country = String::from("Austria");Package::new(sender_country, recipient_country, -2210);}#[test]fn create_international_package() {let sender_country = String::from("Spain");let recipient_country = String::from("Russia");let package = Package::new(sender_country, recipient_country, 1200);assert!(package.is_international());}#[test]fn create_local_package() {let sender_country = String::from("Canada");let recipient_country = sender_country.clone();let package = Package::new(sender_country, recipient_country, 1200);assert!(!package.is_international());}#[test]fn calculate_transport_fees() {let sender_country = String::from("Spain");let recipient_country = String::from("Spain");let cents_per_gram = 3;let package = Package::new(sender_country, recipient_country, 1500);assert_eq!(package.get_fees(cents_per_gram), 4500);assert_eq!(package.get_fees(cents_per_gram * 2), 9000);}
}
解析

根据意思,补全结构体的方法实现,对比是否为同一个地区,判断是否相同,以及计算费用,比较简单。

rust">// structs3.rs
//
// Structs contain data, but can also have logic. In this exercise we have
// defined the Package struct and we want to test some logic attached to it.
// Make the code compile and the tests pass!
//
// Execute `rustlings hint structs3` or use the `hint` watch subcommand for a
// hint.#[derive(Debug)]
struct Package {sender_country: String,recipient_country: String,weight_in_grams: i32,
}impl Package {fn new(sender_country: String, recipient_country: String, weight_in_grams: i32) -> Package {if weight_in_grams <= 0 {panic!("Can not ship a weightless package.")} else {Package {sender_country,recipient_country,weight_in_grams,}}}fn is_international(&self) -> bool {// Something goes here...&self.sender_country != &self.recipient_country}fn get_fees(&self, cents_per_gram: i32) -> i32 {// Something goes here...&self.weight_in_grams * cents_per_gram}
}#[cfg(test)]
mod tests {use super::*;#[test]#[should_panic]fn fail_creating_weightless_package() {let sender_country = String::from("Spain");let recipient_country = String::from("Austria");Package::new(sender_country, recipient_country, -2210);}#[test]fn create_international_package() {let sender_country = String::from("Spain");let recipient_country = String::from("Russia");let package = Package::new(sender_country, recipient_country, 1200);assert!(package.is_international());}#[test]fn create_local_package() {let sender_country = String::from("Canada");let recipient_country = sender_country.clone();let package = Package::new(sender_country, recipient_country, 1200);assert!(!package.is_international());}#[test]fn calculate_transport_fees() {let sender_country = String::from("Spain");let recipient_country = String::from("Spain");let cents_per_gram = 3;let package = Package::new(sender_country, recipient_country, 1500);assert_eq!(package.get_fees(cents_per_gram), 4500);assert_eq!(package.get_fees(cents_per_gram * 2), 9000);}
}

http://www.ppmy.cn/devtools/120838.html

相关文章

24.2.29蓝桥杯|单位换算--8道题

本篇或者本系列文章使用蓝桥云课平台&#xff0c;借助CSDN梳理思路&#xff0c;给自己做一个电子笔记 单位换算类题目注意事项&#xff1a; 在参加蓝桥杯等编程竞赛时&#xff0c;进行单位换算是一个常见的题目类型&#xff0c;特别是涉及到数据存储和传输的问题。在处理单位换…

SQL高级语法

聚合函数 SELECT vendor_id, AVG(price) AS avg_price FROM Products WHERE price > 50GROUP BY vendor_id HAVING AVG(price) > 100 ORDER BY avg_price DESC; PARTITION OVER用于在分区内进行计算。它可以在每个分区内对数据进行排序、聚合、分组等操作。 SELECT id, n…

priority_queue优先队列

**优先队列** 使用函数库实现&#xff0c;头文件<queue> 1&#xff09;大根堆&#xff08;默认&#xff09;&#xff1a;priority_queue<队列中元素类型> 队列名&#xff1b; 小根堆&#xff1a;&#xff08;实现可向元素*-1再入最大优先队列&#xff09; prio…

力扣9.28

377. 组合总和 Ⅳ 给你一个由 不同 整数组成的数组 nums &#xff0c;和一个目标整数 target 。请你从 nums 中找出并返回总和为 target 的元素组合的个数。 题目数据保证答案符合 32 位整数范围。 数据范围 1 < nums.length < 2001 < nums[i] < 1000nums 中的…

Windows下jenkins执行远程sh脚本中文乱码问题

找到jenkins的安装目录下的jenkins.xml文件&#xff0c;在启动参数后面加上-Dfile.encodingutf-8 然后在服务里重启jenkins服务即可

网络协议的作用是什么

在现代网络环境中&#xff0c;各种设备之间的有效通信离不开网络协议。网络协议是计算机网络中进行信息交换的规则和标准。它们定义了数据传输的格式、顺序、错误处理、以及设备如何相互识别等重要方面。本文将深入探讨网络协议的作用及其在网络通信中的重要性。 什么是网络协…

深化专业,广纳技能,构建软实力

一、引言 ----  随着人工智能&#xff08;AI&#xff09;和生成式人工智能&#xff08;AIGC&#xff09;如ChatGPT、Midjourney、Claude等大语言模型的持续涌现&#xff0c;AI辅助编程工具日益普及&#xff0c;程序员的工作方式正在经历深刻的变革。这种变革既带来了对部分编…

sql注入工具升级:自动化时间盲注、布尔盲注

项目地址&#xff1a;https://github.com/iamnotamaster/sql-injecter 给我之前写的sql注入脚本进行了一些升级&#xff0c;此文章就是对升级内容的分析&#xff0c;升级内容如下&#xff1a; 使用占位符foo来填充payload里需要经常修改的部分 自动判断循环 支持爆破和二分查…