Rust 编程中的结构
Rust 中的结构是用户定义的数据类型。它们包含用于定义其具体实例的字段。
我们在 struct 关键字的帮助下定义struct,后跟我们希望为 struct 起的名字。struct 的名称应该描述我们正在其中分组的数据块的重要性。
语法
struct Employee {
id: i32,
name: String,
leaves: i8,
}上面的语法包含 struct 的名称,在大括号中,我们有不同的字段,即类型为i32的id、name和leaves。
创建实例
为了创建 Employee 结构的实例,我们执行类似这样的操作
fn main() {
let emp1 = Employee {
id : 10602,
name : String::from("Mukul"),
leaves : 9
};
println!("{:?}",emp1);
}输出
Employee { id: 10602, name: "Mukul", leaves: 9 }上面的结构实例不可变;我们可以通过添加mut关键字使其可变。
示例
#![allow(unused)]
#[derive(Debug)]
struct Employee {
id: i32,
name: String,
leaves: i8,
}
fn main() {
let mut emp1 = Employee {
id : 10602,
name : String::from("Mukul"),
leaves : 9
};
println!("{:?}",emp1);
emp1.id = 10603;
println!("{:?}",emp1);
}输出
Employee { id: 10602, name: "Mukul", leaves: 9 }
Employee { id: 10603, name: "Mukul", leaves: 9 }单位结构
我们还可以在 Rust 中拥有不包含任何字段的结构。它们很少有用,但可以与其他功能结合使用。
示例
#![allow(unused)]
#[derive(Debug)]
struct Person;
fn main() {
let p = Person;
println!("{:?}",p);
}输出
Person
元组结构
第三种类型的结构称为元组结构;它们包含一个或多个用逗号分隔的值。
示例
#![allow(unused)]
#[derive(Debug)]
struct Color(u8, u8, u8);
fn main() {
let white = Color(1, 1, 1);
let Color(r, g, b) = white;
println!("White = rgb({}, {}, {})", r, g, b);
}输出
White = rgb(1, 1, 1)
广告
数据结构
网络
关系型数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP