本文结合2个代码实例主要介绍了rust函数定义方法,struct结构体定义、struct方法及关联函数等相关基础知识。
代码1:
main.rc
#[derive(Debug)]
//定义一个结构体
struct Ellipse {
max_semi_axis: u32,
min_semi_axis: u32,
}
fn main() {
//椭圆,结构体实例化
let ell = Ellipse {
max_semi_axis: 10,
min_semi_axis: 8,
};
println!("{:#?}", ell);
println!(
"椭圆的长半轴={},椭圆的短半轴={},椭圆的面积={}",
ell.max_semi_axis,
ell.min_semi_axis,
area(&ell)
);
}
//计算椭圆的面积
fn area(ell:&Ellipse) -> f64 {
3.14 * ell.max_semi_axis as f64 * ell.min_semi_axis as f64
}
运行如下:
代码2:
main.rc
#[derive(Debug)]
//定义一个结构体
struct Ellipse {
max_semi_axis: u32,
min_semi_axis: u32,
}
//struct方法
impl Ellipse {
//计算椭圆的面积
fn area(&self) -> f64 {
3.14 * self.max_semi_axis as f64 * self.min_semi_axis as f64
}
//关联函数
fn round(size: u32) -> Ellipse {
Ellipse {
max_semi_axis: size,
min_semi_axis: size,
}
}
}
fn main() {
//椭圆,结构体实例化
let ell = Ellipse {
max_semi_axis: 10,
min_semi_axis: 8,
};
println!("{:#?}", ell);
println!(
"椭圆的长半轴={},椭圆的短半轴={},椭圆的面积={}",
ell.max_semi_axis,
ell.min_semi_axis,
ell.area()
);
println!("-----------------------------------------");
//圆,结构体实例化
let r = Ellipse::round(15);
println!("{:#?}", r);
println!(
"圆的长半轴={},圆的短半轴={},圆的面积={}",
r.max_semi_axis,
r.min_semi_axis,
r.area()
);
}
运行结果如下: