頭條地址: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 協議》,轉載必須註明作者和本文連結