Rust3 Using Structs to Structure Related Data Enums and Pattern Matching

2023-11-10 07:30

本文主要是介绍Rust3 Using Structs to Structure Related Data Enums and Pattern Matching,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Rust学习笔记

Rust编程语言入门教程课程笔记

参考教材: The Rust Programming Language (by Steve Klabnik and Carol Nichols, with contributions from the Rust Community)

Lecture 5: Using Structs to Structure Related Data

// define a struct
#[derive(Debug)]
struct User{username: String,email: String,sign_in_count: u64,active: bool, // trailing comma is allowed
}// rectangle struct
#[derive(Debug)]
struct Rectangle{width: u32,height: u32,
}impl Rectangle{// method to calculate the area of a rectanglefn area(&self) -> u32{self.width * self.height}// method to check if a rectangle can hold another rectanglefn can_hold(&self, other: &Rectangle) -> bool{self.width > other.width && self.height > other.height}// associated functionfn square(size: u32) -> Rectangle{ // does not take self as parameterRectangle{width: size,height: size,}}
}fn main() {// create an instance of structlet mut user = User{email: String::from("abc@gmail.com"),username: String::from("abc"),active: true,sign_in_count: 1,};println!("{},{},{},{}", user.email, user.username, user.active, user.sign_in_count);// change the value of the structuser.email = String::from("abc_plus@gmail.com");println!("{}", user.email);// create a new instance of struct using functionlet user2 = build_user(String::from("user2@gmail.com"), String::from("user2"));// create a new instance of struct using struct update syntaxlet _user3 = User{email: String::from("user3@gmail.com"),username: String::from("user3"),..user2 // use the remaining fields from user2};// create a tuple structstruct Color(i32, i32, i32);let _black = Color(0, 0, 0);// create a unit struct//struct UnitStruct;// no fields//calculate the area of a rectanglelet rect = Rectangle{width: 30,height: 50,};// create a method for the structprintln!("The area of the rectangle is {} square pixels.", rect.area());println!("{:#?}", rect);let rect2 = Rectangle{width: 10,height: 40,};println!("Can rect hold rect2? {}", rect.can_hold(&rect2));// create a square using associated functionlet square = Rectangle::square(3);println!("The area of the square is {} square pixels.", square.area());
}// create a function that returns a struct
fn build_user(email: String, username: String) -> User{User{email: email,username: username,active: true,sign_in_count: 1,}
}

Lecture 6: Enums and Pattern Matching

//create an enum
#[derive(Debug)]
enum IpAddrKind{V4,V6,
}//create an enum with data
// enum IpAddrKindWithData{
//     V4(u8, u8, u8, u8),
//     V6(String),
// }//four = IpAddrKind::V4(127, 0, 0, 1);#[derive(Debug)]
struct IpAddr {kind: IpAddrKind,address: String,
}#[derive(Debug)]
enum Message{Quit,Move {x: i32, y: i32},Write(String),ChangeColor(i32, i32, i32),
}impl Message{fn call(&self){//method body would be defined hereprintln!("Message: {:?}", self);}
}
#[derive(Debug)]
enum Coin{Penny,Nickel,Dime,Quarter,
}
#[derive(Debug)]
enum CoinWithData{Penny,Nickel,Dime,Quarter(UsState),
}
#[derive(Debug)]
enum UsState{//Alabama,Alaska,// --snip--
}fn main() {//create an instance of the enumlet four = IpAddrKind::V4;let six = IpAddrKind::V6;//print the enumroute(four);route(six);route(IpAddrKind::V4);route(IpAddrKind::V6);//create an enum with datalet home = IpAddr {kind: IpAddrKind::V4,address: String::from("127.0.0.1"),};println!("home: {:?}", home);println!("kind: {:?}", home.kind);println!("address: {:?}", home.address);let q = Message::Quit;let m = Message::Move{x: 1, y: 2};let w = Message::Write(String::from("hello"));let c = Message::ChangeColor(1, 2, 3);q.call();m.call();w.call();c.call();//print m.x + m.yif let Message::Move{x, y} = m{println!("x + y = {}", x + y);}//option enumlet some_number = Some(5);let some_string = Some("a string");let absent_number: Option<i32> = None;println!("some_number: {:?}", some_number);println!("some_string: {:?}", some_string);println!("absent_number: {:?}", absent_number);let six = plus_one(some_number);let none = plus_one(absent_number);println!("six: {:?}", six);println!("none: {:?}", none);//matchlet coin_1 = Coin::Penny;let coin_5 = Coin::Nickel;let coin_10 = Coin::Dime;let coin_25 = Coin::Quarter;println!("coin_1: {:?}", coin_1);println!("coin_5: {:?}", coin_5);println!("coin_10: {:?}", coin_10);println!("coin_25: {:?}", coin_25);let datacoin_1 = CoinWithData::Penny;let datacon_5 = CoinWithData::Nickel;let datacoin_10 = CoinWithData::Dime;let datacoin_25 = CoinWithData::Quarter(UsState::Alaska);println!("datacoin_1: {:?}", datacoin_1);println!("datacon_5: {:?}", datacon_5);println!("datacoin_10: {:?}", datacoin_10);println!("datacoin_25: {:?}", datacoin_25);value_in_cents(coin_1);value_in_cents_binding_value(datacoin_25);let v = Some(7u8);match v {Some(1) => println!("one"),Some(3) => println!("three"),Some(5) => println!("five"),Some(7) => println!("seven"),_ => println!("anything"),//default};//if letif let Some(3) = v {println!("three");}else{println!("anything");}}fn route(ip_kind: IpAddrKind) {println!("ip_kind: {:?}", ip_kind);
}fn value_in_cents(coin: Coin) -> u32{match coin{Coin::Penny => {println!("Lucky penny!");1},Coin::Nickel => 5,Coin::Dime => 10,Coin::Quarter => 25,}
}fn value_in_cents_binding_value(coin: CoinWithData) -> u32{match coin{CoinWithData::Penny => {println!("Lucky penny!");1},CoinWithData::Nickel => 5,CoinWithData::Dime => 10,//Coin::Quarter => 25,CoinWithData::Quarter(state) => {println!("State quarter from {:?}!", state);25},}
}fn plus_one(x: Option<i32>) -> Option<i32>{match x{ //match is exhaustiveNone => None,Some(i) => Some(i + 1),}
}

这篇关于Rust3 Using Structs to Structure Related Data Enums and Pattern Matching的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/381234

相关文章

HTML5 data-*自定义数据属性的示例代码

《HTML5data-*自定义数据属性的示例代码》HTML5的自定义数据属性(data-*)提供了一种标准化的方法在HTML元素上存储额外信息,可以通过JavaScript访问、修改和在CSS中使用... 目录引言基本概念使用自定义数据属性1. 在 html 中定义2. 通过 JavaScript 访问3.

解读静态资源访问static-locations和static-path-pattern

《解读静态资源访问static-locations和static-path-pattern》本文主要介绍了SpringBoot中静态资源的配置和访问方式,包括静态资源的默认前缀、默认地址、目录结构、访... 目录静态资源访问static-locations和static-path-pattern静态资源配置

论文翻译:arxiv-2024 Benchmark Data Contamination of Large Language Models: A Survey

Benchmark Data Contamination of Large Language Models: A Survey https://arxiv.org/abs/2406.04244 大规模语言模型的基准数据污染:一项综述 文章目录 大规模语言模型的基准数据污染:一项综述摘要1 引言 摘要 大规模语言模型(LLMs),如GPT-4、Claude-3和Gemini的快

CentOS下mysql数据库data目录迁移

https://my.oschina.net/u/873762/blog/180388        公司新上线一个资讯网站,独立主机,raid5,lamp架构。由于资讯网是面向小行业,初步估计一两年内访问量压力不大,故,在做服务器系统搭建的时候,只是简单分出一个独立的data区作为数据库和网站程序的专区,其他按照linux的默认分区。apache,mysql,php均使用yum安装(也尝试

使用Spring Boot集成Spring Data JPA和单例模式构建库存管理系统

引言 在企业级应用开发中,数据库操作是非常重要的一环。Spring Data JPA提供了一种简化的方式来进行数据库交互,它使得开发者无需编写复杂的JPA代码就可以完成常见的CRUD操作。此外,设计模式如单例模式可以帮助我们更好地管理和控制对象的创建过程,从而提高系统的性能和可维护性。本文将展示如何结合Spring Boot、Spring Data JPA以及单例模式来构建一个基本的库存管理系统

15 组件的切换和对组件的data的使用

划重点 a 标签的使用事件修饰符组件的定义组件的切换:登录 / 注册 泡椒鱼头 :微辣 <!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-

12C 新特性,MOVE DATAFILE 在线移动 包括system, 附带改名 NID ,cdb_data_files视图坏了

ALTER DATABASE MOVE DATAFILE  可以改名 可以move file,全部一个命令。 resue 可以重用,keep好像不生效!!! system照移动不误-------- SQL> select file_name, status, online_status from dba_data_files where tablespace_name='SYSTEM'

SIGMOD-24概览Part7: Industry Session (Graph Data Management)

👇BG3: A Cost Effective and I/O Efficient Graph Database in ByteDance 🏛机构:字节 ➡️领域: Information systems → Data management systemsStorage management 📚摘要:介绍了字节新提出的ByteGraph 3.0(BG3)模型,用来处理大规模图结构数据 背景

java.sql.SQLException: No data found

Java代码如下: package com.accord.utils;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.ResultSetMetaData;import

leetcode#10. Regular Expression Matching

题目 Implement regular expression matching with support for ‘.’ and ‘*’. '.' Matches any single character.'*' Matches zero or more of the preceding element.The matching should cover the entire input