什么是struct?
struct:结构体,可以理解为JAVA中的对象
定义struct
使用struct关键字
struct Cuboid {//长方体
length: f64,//长
width: f64,//宽
height: f64,//高
}
//初始化,每一个字段都要复制,不然编译不过
fn main() {
let cuboid = Cuboid {
width: 30.7,
length: 40.9,
height: 10.5
};
println!("获取长字段的值:{}",cuboid.length);
}
输出:
获取长字段的值:40.9
可以对实例用mut关键字修饰,mut修饰的struct实例其所有字段都是可变的
fn main() {
let mut cuboid = Cuboid {
length: 40.9,
width: 30.7,
height: 10.5
};
cuboid.length = 10.1;
println!("获取长字段的值:{}",cuboid.length);
}
输出:
获取长字段的值:10.1
struct也可以作为函数返回值
fn main() {
let cuboid1 = return_struct();
}
fn return_struct()->Cuboid{
Cuboid {
length: 40.9,
width: 30.7,
height: 10.5
}
}
输出:
返回struct:Cuboid {
length: 40.9,
width: 30.7,
height: 10.5,
}
struct更新语法
基于一个struct实例,想创建另一个实例时,我们可以使用struct更新语法
fn main() {
let cuboid = Cuboid {
length: 40.9,
width: 30.7,
height: 10.5,
};
let cuboid2 = Cuboid {
length: cuboid.length,//部分字段相同时
width: 30.7,
height: 10.5,
};
let cuboid2 = Cuboid {
..cuboid//全部字段相同时,直接用..表示
};
}
Tuple struct
fn main() {
let color = Color(0, 0, 0);
let point = Point(108.9, 89.1);
}
struct Color (u32,u32,u32);
struct Point(f64, f64);
Unit Like struct
没有字段的struct
struct Cuboid {
}
struct方法与函数
方法和函数类似:fn、方法名、参数、返回值
不同之处:
1、方法定义在struct内
2、第一个参数为self
3、对struct使用impl关键字,定义impl方法块
接下来尝试一个例子
fn main() {
let mut cuboid = Cuboid {
length: 40.9,
width: 30.7,
height: 10.5,
};
let volume = cuboid.volume();
println!("长方体体积:{}", volume);
println!("长方体实体:{:#?}", cuboid);
let cube = Cuboid::cube(30f64);
let cube_volume = cube.volume();
println!("正方体体积:{}", cube_volume);
println!("正方体实体:{:#?}", cube);//对宏输出内容格式化
}
#[derive(Debug)]//用Debug调试模式
struct Cuboid {
length: f64,
width: f64,
height: f64,
}
impl Cuboid {
//关联函数通常用于构造器
fn cube(size: f64) -> Cuboid {
Cuboid {
width: size,
length: size,
height: size,
}
}
//计算体积函数
fn volume(&self) -> f64 {
self.width * self.length * self.height
}
}
输出:
长方体体积:13184.114999999998
长方体实体:Cuboid {
length: 40.9,
width: 30.7,
height: 10.5,
}
正方体体积:27000
正方体实体:Cuboid {
length: 30.0,
width: 30.0,
height: 30.0,
}