rust权威指南笔记(三)

第5章 使用结构体来组织相关联的数据

use std::string::String;
#[derive(Debug)]
struct User{
    name: String,
    age: u32,
}

struct Color(u8,u8,u8);

fn main(){
    let mut u1 = User{
        name: String::from("小明"),
        age: 17,
    };
    println!("{:?}",u1);
    println!("u1姓名是{}",u1.name);  //查看字段
    u1.name = String::from("小红"); // 修改字段,注意u1要是mut的
    println!("{}",u1.name);
    let u1_sex = &u1.sex;          // 不可移动要借用,不然会使u1无效
    println!("{:?}",u1);
    let black = Color(0,0,0);
    println!("black = ({},{},{})",black.0,black.1,black.2); //访问元组结构体
}

结构体必须掌握字段值所有权,因为结构体失效的时候会释放所有字段。

在变量名与字段名相同时使用简化版的字段初始化方法

使用结构体更新语法根据其他实例创建新实例

第6章 枚举与模式匹配

枚举类型用来分类 附加属性可以定义成元组或结构体

use std::string::String;

#[derive(Debug)]
enum Shape1{
    Rectangle,Circle
}

#[derive(Debug)]
enum Shape2{
    Rectangle(f64,f64),
    Circle(f64)
}

#[derive(Debug)]
enum Shape3{
    Rectangle{height:f64,width:f64},
    Circle{radius:f64}
}

fn main() {
    let shape1 = Shape1::Rectangle;
    let shape2 = Shape2::Circle(3.0);
    let shape3 = Shape3::Rectangle{height:3.0,width:4.0};
    // match 所有返回值表达式的类型必须一样
    match shape2{
        Shape2::Rectangle(a,b)=>{ //如果把枚举类附加属性定义成元组,在 match 块中需要临时指定一个名字
            println!("矩形的面积是{}",a*b);
        },
        Shape2::Circle(r)=>{
            println!("圆形的面积是{}",3.14*r*r);
        }
    }

    match shape3{
        Shape3::Rectangle{height,width}=>{
            println!("矩形的面积是{}",height*width);
        },
        Shape3::Circle{radius}=>{
            println!("圆形的面积是{}",3.14*radius*radius);
        }
    }

    //match处理例外情况
    let s = "abcd";
    match s {
        "abc"=>println!("Yes"),
        _=>{}
    }

    //Option枚举类,这个类用于填补 Rust 不支持 null 引用的空白
    // enum Option<T> {
    //     Some(T),
    //     None,
    // }
    let opt1 = Option::Some("Hello"); // let opt1 = Some("Hello"); Option可以省略
    let opt2: Option<&str> = Option::None;//变量刚开始是空值,要标明类型

    match opt2{
        Option::Some(something)=>{
            println!("{}",something);
        },
        Option::None=>{
            println!("there is nothing!");
        }
    }

}