#[derive(Debug)]
struct Rectangle {
//结构体的定义
width: u32,
height: u32,
}
//结构体中的方法定义
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
fn can_hold(&self, other: &Rectangle) -> bool {
self.width > other.width && self.height > other.height
}
//不把&self做为第一个参数的函数,叫关联函数,我认为也叫静态函数
fn build(width:u32,height:u32) -> Rectangle {
Rectangle {
width:width,
height:height,
}
}
}
fn main() {
//定义结构体变量,并初化值
let a = Rectangle {
width: 20,
height: 30,
};
let b = Rectangle::build(10,20);
println!("{:#?}", a); //打印格式化结构信息、结构体必须用 #[derive(Debug)]
println!("area={}", a.area()); //调用结构体的方法、求面积
println!("{}",a.can_hold(&b)); //是否可以完全包含指定矩形
}
运行结果如下:
Rectangle {
width: 20,
height: 30,
}
area=600
true