struct method
作用: 用来操作结构体实例
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
}
fn main() {
let rect1 = Rectangle { width: 30, height: 50 };
println!("rect1's area is {}", rect1.area());
}
因为是操作结构体实例,所以需要在形参中添加 &self
fn area(&self)
使用是这样的
rect1.area()
struct function
作用:不依赖结构体实例
#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn create(width: u32, height: u32) -> Rectangle {
Rectangle { width, height }
}
}
fn main() {
let rect = Rectangle::create(30, 50);
println!("{:?}", rect);
}
不需要在形参中添加&self
fn create(width: u32, height: u32)
使用是这样的
let rect = Rectangle::create(30, 50);