• RustDay05------Exercise[31-40]


    31.结构体申明

    结构体在这里给了三种声明样式

    (1)字典样式的键值对(使用花括号)

    (2)元组样式的数值元组(使用圆括号)

    (3)空结构体,可以被格式化输出名字

    1. // structs1.rs
    2. // Address all the TODOs to make the tests pass!
    3. // Execute `rustlings hint structs1` or use the `hint` watch subcommand for a hint.
    4. // I AM NOT DONE
    5. struct ColorClassicStruct {
    6. // TODO: Something goes here
    7. red:u8,
    8. green:u8,
    9. blue:u8,
    10. }
    11. struct ColorTupleStruct(u8,u8,u8);
    12. #[derive(Debug)]
    13. struct UnitLikeStruct;
    14. #[cfg(test)]
    15. mod tests {
    16. use super::*;
    17. #[test]
    18. fn classic_c_structs() {
    19. // TODO: Instantiate a classic c struct!
    20. let green =ColorClassicStruct{red:0,green:255,blue:0};
    21. assert_eq!(green.red, 0);
    22. assert_eq!(green.green, 255);
    23. assert_eq!(green.blue, 0);
    24. }
    25. #[test]
    26. fn tuple_structs() {
    27. // TODO: Instantiate a tuple struct!
    28. let green =ColorTupleStruct(0,255,0);
    29. assert_eq!(green.0, 0);
    30. assert_eq!(green.1, 255);
    31. assert_eq!(green.2, 0);
    32. }
    33. #[test]
    34. fn unit_structs() {
    35. // TODO: Instantiate a unit-like struct!
    36. let unit_like_struct =UnitLikeStruct;
    37. let message = format!("{:?}s are fun!", unit_like_struct);
    38. assert_eq!(message, "UnitLikeStructs are fun!");
    39. }
    40. }

    32.结构体的解包

    我们可以在一个结构体实例里面使用..otherStruct来对otherStruct里面未被定义的变量原封不动解包到该结构体实例里面

    1. // structs2.rs
    2. // Address all the TODOs to make the tests pass!
    3. // Execute `rustlings hint structs2` or use the `hint` watch subcommand for a hint.
    4. // I AM NOT DONE
    5. #[derive(Debug)]
    6. struct Order {
    7. name: String,
    8. year: u32,
    9. made_by_phone: bool,
    10. made_by_mobile: bool,
    11. made_by_email: bool,
    12. item_number: u32,
    13. count: u32,
    14. }
    15. fn create_order_template() -> Order {
    16. Order {
    17. name: String::from("Bob"),
    18. year: 2019,
    19. made_by_phone: false,
    20. made_by_mobile: false,
    21. made_by_email: true,
    22. item_number: 123,
    23. count: 0,
    24. }
    25. }
    26. #[cfg(test)]
    27. mod tests {
    28. use super::*;
    29. #[test]
    30. fn your_order() {
    31. let order_template = create_order_template();
    32. // TODO: Create your own order using the update syntax and template above!
    33. let your_order = Order{
    34. name: String::from("Hacker in Rust"),
    35. count:1,
    36. ..order_template
    37. };
    38. assert_eq!(your_order.name, "Hacker in Rust");
    39. assert_eq!(your_order.year, order_template.year);
    40. assert_eq!(your_order.made_by_phone, order_template.made_by_phone);
    41. assert_eq!(your_order.made_by_mobile, order_template.made_by_mobile);
    42. assert_eq!(your_order.made_by_email, order_template.made_by_email);
    43. assert_eq!(your_order.item_number, order_template.item_number);
    44. assert_eq!(your_order.count, 1);
    45. }
    46. }

    33.类里面的方法除了当前区域内的变量,其他都要加self引用

    1. // structs3.rs
    2. // Structs contain data, but can also have logic. In this exercise we have
    3. // defined the Package struct and we want to test some logic attached to it.
    4. // Make the code compile and the tests pass!
    5. // Execute `rustlings hint structs3` or use the `hint` watch subcommand for a hint.
    6. // I AM NOT DONE
    7. #[derive(Debug)]
    8. struct Package {
    9. sender_country: String,
    10. recipient_country: String,
    11. weight_in_grams: i32,
    12. }
    13. impl Package {
    14. fn new(sender_country: String, recipient_country: String, weight_in_grams: i32) -> Package {
    15. if weight_in_grams <= 0 {
    16. panic!("Can not ship a weightless package.")
    17. } else {
    18. Package {
    19. sender_country,
    20. recipient_country,
    21. weight_in_grams,
    22. }
    23. }
    24. }
    25. fn is_international(&self) -> bool {
    26. // Something goes here...
    27. return self.sender_country!=self.recipient_country
    28. }
    29. fn get_fees(&self, cents_per_gram: i32) -> i32 {
    30. // Something goes here...
    31. return cents_per_gram*self.weight_in_grams
    32. }
    33. }
    34. #[cfg(test)]
    35. mod tests {
    36. use super::*;
    37. #[test]
    38. #[should_panic]
    39. fn fail_creating_weightless_package() {
    40. let sender_country = String::from("Spain");
    41. let recipient_country = String::from("Austria");
    42. Package::new(sender_country, recipient_country, -2210);
    43. }
    44. #[test]
    45. fn create_international_package() {
    46. let sender_country = String::from("Spain");
    47. let recipient_country = String::from("Russia");
    48. let package = Package::new(sender_country, recipient_country, 1200);
    49. assert!(package.is_international());
    50. }
    51. #[test]
    52. fn create_local_package() {
    53. let sender_country = String::from("Canada");
    54. let recipient_country = sender_country.clone();
    55. let package = Package::new(sender_country, recipient_country, 1200);
    56. assert!(!package.is_international());
    57. }
    58. #[test]
    59. fn calculate_transport_fees() {
    60. let sender_country = String::from("Spain");
    61. let recipient_country = String::from("Spain");
    62. let cents_per_gram = 3;
    63. let package = Package::new(sender_country, recipient_country, 1500);
    64. assert_eq!(package.get_fees(cents_per_gram), 4500);
    65. assert_eq!(package.get_fees(cents_per_gram * 2), 9000);
    66. }
    67. }

    34.添加枚举类型以供打印

    1. // enums1.rs
    2. // No hints this time! ;)
    3. // I AM NOT DONE
    4. #[derive(Debug)]
    5. enum Message {
    6. // TODO: define a few types of messages as used below
    7. Quit,
    8. Echo,
    9. Move,
    10. ChangeColor,
    11. }
    12. fn main() {
    13. println!("{:?}", Message::Quit);
    14. println!("{:?}", Message::Echo);
    15. println!("{:?}", Message::Move);
    16. println!("{:?}", Message::ChangeColor);
    17. }

    35.对枚举类型实现方法

    使用向enumeration type添加一个方法

    1. // enums2.rs
    2. // Execute `rustlings hint enums2` or use the `hint` watch subcommand for a hint.
    3. // I AM NOT DONE
    4. #[derive(Debug)]
    5. enum Message {
    6. // TODO: define the different variants used below
    7. Move { x: i32, y: i32 },
    8. Echo(String),
    9. ChangeColor(u8, u8, u8),
    10. Quit,
    11. }
    12. // impl用于向一个类型(可以是结构体、枚举、特质 trait 等)添加方法或实现 trait,从而为该类型定义特定的行为。
    13. impl Message {
    14. fn call(&self) {
    15. println!("{:?}", &self);
    16. }
    17. }
    18. fn main() {
    19. let messages = [
    20. Message::Move { x: 10, y: 30 },
    21. Message::Echo(String::from("hello world")),
    22. Message::ChangeColor(200, 255, 255),
    23. Message::Quit,
    24. ];
    25. for message in &messages {
    26. message.call();
    27. }
    28. }

    36.使用match对枚举类型的方法进行匹配

    match 匹配格式如下

    1. match vailableType {
    2. namespace1::fun1(args1,args2) => {
    3. return self.fun1(args1,args2)
    4. }
    5. }
    1. // enums3.rs
    2. // Address all the TODOs to make the tests pass!
    3. // Execute `rustlings hint enums3` or use the `hint` watch subcommand for a hint.
    4. // I AM NOT DONE
    5. enum Message {
    6. // TODO: implement the message variant types based on their usage below
    7. ChangeColor((u8,u8,u8)),
    8. Echo(String),
    9. Move(Point ),
    10. Quit,
    11. // state.process(Message::ChangeColor((255, 0, 255)));
    12. // state.process(Message::Echo(String::from("hello world")));
    13. // state.process(Message::Move(Point { x: 10, y: 15 }));
    14. // state.process(Message::Quit);
    15. }
    16. struct Point {
    17. x: u8,
    18. y: u8,
    19. }
    20. struct State {
    21. color: (u8, u8, u8),
    22. position: Point,
    23. quit: bool,
    24. }
    25. impl State {
    26. fn change_color(&mut self, color: (u8, u8, u8)) {
    27. self.color = color;
    28. }
    29. fn quit(&mut self) {
    30. self.quit = true;
    31. }
    32. fn echo(&self, s: String) {
    33. println!("{}", s);
    34. }
    35. fn move_position(&mut self, p: Point) {
    36. self.position = p;
    37. }
    38. fn process(&mut self, message: Message) {
    39. // TODO: create a match expression to process the different message variants
    40. match message {
    41. Message::ChangeColor(objects) => {
    42. return self.change_color((objects.0,objects.1,objects.2))
    43. }
    44. Message::Echo(string) => {
    45. return self.echo(string)
    46. }
    47. Message::Move(point) => {
    48. return self.move_position( point)
    49. }
    50. Message::Quit => {
    51. return self.quit()
    52. }
    53. }
    54. }
    55. }
    56. #[cfg(test)]
    57. mod tests {
    58. use super::*;
    59. #[test]
    60. fn test_match_message_call() {
    61. let mut state = State {
    62. quit: false,
    63. position: Point { x: 0, y: 0 },
    64. color: (0, 0, 0),
    65. };
    66. state.process(Message::ChangeColor((255, 0, 255)));
    67. state.process(Message::Echo(String::from("hello world")));
    68. state.process(Message::Move(Point { x: 10, y: 15 }));
    69. state.process(Message::Quit);
    70. assert_eq!(state.color, (255, 0, 255));
    71. assert_eq!(state.position.x, 10);
    72. assert_eq!(state.position.y, 15);
    73. assert_eq!(state.quit, true);
    74. }
    75. }

    37.将&str转成String

    可以调用&str对象的to_string()方法或者使用String::from(&str)将其转换

    1. // strings1.rs
    2. // Make me compile without changing the function signature!
    3. // Execute `rustlings hint strings1` or use the `hint` watch subcommand for a hint.
    4. // I AM NOT DONE
    5. fn main() {
    6. let answer = current_favorite_color();
    7. println!("My current favorite color is {}", answer);
    8. }
    9. fn current_favorite_color() -> String {
    10. String::from("blue")
    11. }

    38.在比较情况下,Sring和&str会隐式转化去比较

    试运行如下代码:

    1. fn main() {
    2. let string1 = "aaaa".to_string();
    3. let string2 = "aaaa";
    4. if string1 == string2 {
    5. println!("Strings are equal");
    6. } else {
    7. println!("Strings are not equal");
    8. }
    9. }
    10. //输出 Strings are equal
    1. // strings2.rs
    2. // Make me compile without changing the function signature!
    3. // Execute `rustlings hint strings2` or use the `hint` watch subcommand for a hint.
    4. // I AM NOT DONE
    5. fn main() {
    6. let word = String::from("green"); // Try not changing this line :)
    7. if is_a_color_word(word) {
    8. println!("That is a color word I know!");
    9. } else {
    10. println!("That is not a color word I know.");
    11. }
    12. }
    13. fn is_a_color_word(attempt: String) -> bool {
    14. //对象类型不一致 都返回false
    15. // attempt == "green" || attempt == "blue" || attempt == "red"
    16. // let attempt = attempt.to_string();
    17. println!("{}|{}|{}",attempt == "green" ,attempt == "blue" ,attempt == "red");
    18. attempt == "green" || attempt == "blue" || attempt == "red"
    19. }

    39.&str类型清除两边空白与&str的replace

    通常情况下&str使用方法后都会变成String

    1. // strings3.rs
    2. // Execute `rustlings hint strings3` or use the `hint` watch subcommand for a hint.
    3. // I AM NOT DONE
    4. fn trim_me(input: &str) -> String {
    5. // TODO: Remove whitespace from both ends of a string!
    6. input.trim().to_string()
    7. }
    8. fn compose_me(input: &str) -> String {
    9. // TODO: Add " world!" to the string! There's multiple ways to do this!
    10. input.trim().to_string()+" world!"
    11. }
    12. fn replace_me(input: &str) -> String {
    13. // TODO: Replace "cars" in the string with "balloons"!
    14. input.replace("cars","balloons")
    15. }
    16. #[cfg(test)]
    17. mod tests {
    18. use super::*;
    19. #[test]
    20. fn trim_a_string() {
    21. assert_eq!(trim_me("Hello! "), "Hello!");
    22. assert_eq!(trim_me(" What's up!"), "What's up!");
    23. assert_eq!(trim_me(" Hola! "), "Hola!");
    24. }
    25. #[test]
    26. fn compose_a_string() {
    27. assert_eq!(compose_me("Hello"), "Hello world!");
    28. assert_eq!(compose_me("Goodbye"), "Goodbye world!");
    29. }
    30. #[test]
    31. fn replace_a_string() {
    32. assert_eq!(replace_me("I think cars are cool"), "I think balloons are cool");
    33. assert_eq!(replace_me("I love to look at cars"), "I love to look at balloons");
    34. }
    35. }

    40.&在调用方法和函数之后会变成哪些类型

    看看就好,记住中间保持&str的特例函数和切片(trim()函数和切片变成&str)

    1. // strings4.rs
    2. // Ok, here are a bunch of values-- some are `String`s, some are `&str`s. Your
    3. // task is to call one of these two functions on each value depending on what
    4. // you think each value is. That is, add either `string_slice` or `string`
    5. // before the parentheses on each line. If you're right, it will compile!
    6. // No hints this time!
    7. // I AM NOT DONE
    8. fn string_slice(arg: &str) {
    9. println!("{}", arg);
    10. }
    11. fn string(arg: String) {
    12. println!("{}", arg);
    13. }
    14. fn main() {
    15. string_slice("blue");
    16. string("red".to_string());
    17. string(String::from("hi"));
    18. string("rust is fun!".to_owned());
    19. string("nice weather".into());
    20. string(format!("Interpolation {}", "Station"));
    21. string_slice(&String::from("abc")[0..1]);
    22. string_slice(" hello there ".trim());
    23. string("Happy Monday!".to_string().replace("Mon", "Tues"));
    24. string("mY sHiFt KeY iS sTiCkY".to_lowercase());
    25. }

  • 相关阅读:
    二级指针 杂记
    (附源码)Springboot酒店预订管理系统 毕业设计 092101
    来了~worthington组织培养术语第二弹!
    基于个性化推荐的图书网站设计与实现
    算法拾遗十四前缀树概念以及不基于比较的排序
    小红书KOC获得“官方认可”丨价值评估模型
    使用windows端MySQL创建数据库
    后疫情时代,河北吉力宝打开传统制造业数字化转型新视角
    商城免费搭建之java商城 开源java电子商务Spring Cloud+Spring Boot+mybatis+MQ+VR全景+b2b2c
    v-if失效原因
  • 原文地址:https://blog.csdn.net/m0_72678953/article/details/133881330