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)

rust 复制代码
// 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 rectangle
    fn area(&self) -> u32{
        self.width * self.height
    }

    // method to check if a rectangle can hold another rectangle
    fn can_hold(&self, other: &Rectangle) -> bool{
        self.width > other.width && self.height > other.height
    }

    // associated function
    fn square(size: u32) -> Rectangle{ // does not take self as parameter
        Rectangle{
            width: size,
            height: size,
        }
    }
}

fn main() {
    // create an instance of struct
    let 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 struct
    user.email = String::from("abc_plus@gmail.com");
    

    println!("{}", user.email);

    // create a new instance of struct using function

    let user2 = build_user(String::from("user2@gmail.com"), String::from("user2"));

    // create a new instance of struct using struct update syntax

    let _user3 = User{
        email: String::from("user3@gmail.com"),
        username: String::from("user3"),
        ..user2 // use the remaining fields from user2
    };

    // create a tuple struct
    struct Color(i32, i32, i32);
    let _black = Color(0, 0, 0);

    // create a unit struct
    //struct UnitStruct;// no fields

    //calculate the area of a rectangle
    let rect = Rectangle{
        width: 30,
        height: 50,
    };

    // create a method for the struct
    println!("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 function
    let 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

rust 复制代码
//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 here
        println!("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 enum
    let four = IpAddrKind::V4;
    let six = IpAddrKind::V6;

    //print the enum
    route(four);
    route(six);
    route(IpAddrKind::V4);
    route(IpAddrKind::V6);

    //create an enum with data
    let 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.y
    if let Message::Move{x, y} = m{
        println!("x + y = {}", x + y);
    }

    //option enum
    let 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);

    //match
    let 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 let
    if 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 exhaustive
        None => None,
        Some(i) => Some(i + 1),
    }
}
相关推荐
商业白皮书2 小时前
杭州企业做 GEO 怎么选服务商?B2B 制造、外贸出海与品牌连锁选型指南
笔记
柯南46682 小时前
【AI开发之Rust】第 8 课:泛型、trait 与 trait 对象
rust·编程语言
商业白皮书2 小时前
密不透风的瑕疵防线:东集SEV400视觉传感器,定义“轻量化”精准检测
笔记
yume_sibai4 小时前
12-Rust 性能优化指南(性能分析 + 内存优化 + SIMD + 并发优化 + 编译器优化 + 基准测试)
开发语言·性能优化·rust
geovindu4 小时前
rust:Builder Pattern
开发语言·设计模式·rust·建造者模式
谢白羽5 小时前
MiniMax-H3 : 4卡 H20-3e一套权重部署实践/8卡H200部署优化实测
笔记·llm·论文·大模型部署·sglang
志尊宝5 小时前
Vue3 零基础每日笔记(024):组件的创建与使用——从 import 到自动导入
前端·vue.js·笔记·前端框架·html5
chnyi6_ya6 小时前
论文阅读笔记:VBVR-Pro 把「用生成来推理」变成一个可训练、可验证、可优化的闭环
论文阅读·笔记
contro1_h6 小时前
关于ArcGIS许可管理器服务无法启动的问题
经验分享·笔记·学习方法
1314lay_10077 小时前
SQL SERVER 修改已创建的表
经验分享·笔记