Rust 编程视频教程对应讲解内容-结构体

视频地址

头条地址:https://www.ixigua.com/i676544267458235648...
B站地址:https://www.bilibili.com/video/av78062009?...
网易云课堂地址:https://study.163.com/course/introduction....

讲解内容

1、定义结构体

struct User {
    username: String,
    email: String,
    sign_in_count: u64,
    active: bool,
}

2、创建结构体实例

let user1 = User {
    email: String::from("someone@example.com"),
    username: String::from("someusername123"),
    active: true,
    sign_in_count: 1,
};

3、修改结构体字段

let mut user1 = User {
    email: String::from("someone@example.com"),
    username: String::from("someusername123"),
    active: true,
    sign_in_count: 1,
};

user1.sign_in_count = 3;

4、参数名字和字段名字同名的简写方法

fn build_user(email: String, username: String) -> User {
    User {
        email,
        username,
        active: true,
        sign_in_count: 1,
    }
}

5、从其它结构体创建实例
正常写法:

let user2 = User {
    email: String::from("another@example.com"),
    username: String::from("anotherusername567"),
    active: user1.active,
    sign_in_count: user1.sign_in_count,
};

简写方法:

let user2 = User {
    email: String::from("another@example.com"),
    username: String::from("anotherusername567"),
    ..user1
};

6、元组结构体
特点:
(1)字段没有名字
(2)圆括号

struct Color(i32, i32, i32);
struct Point(i32, i32, i32);
let black = Color(0, 0, 0);
let origin = Point(0, 0, 0);

7、没有任何字段的类单元结构体
用于在其上实现trait,类似于定义一个没有成员的类,但是有成员函数。

8、打印结构体

#[derive(Debug)]       //添加deprive(Debug)支持打印
struct Rectangle {
    width: u32,
    height: u32,
}

fn main() {
    let rect1 = Rectangle { width: 30, height: 50 };
    println!("rect1 is {:?}", rect1);
}
本作品采用《CC 协议》,转载必须注明作者和本文链接

令狐一冲

讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!