推荐答案
在 Rust 中,结构体方法是通过 impl 块来定义的。结构体方法可以分为两类:实例方法和关联方法。
实例方法
实例方法是通过结构体的实例来调用的,第一个参数通常是 self,表示当前结构体的实例。
// www.javascriptcn.com code example
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
// 实例方法
fn area(&self) -> u32 {
self.width * self.height
}
}
fn main() {
let rect = Rectangle { width: 30, height: 50 };
println!("Area: {}", rect.area());
}关联方法
关联方法不依赖于结构体的实例,通常用于构造函数或其他不依赖于实例的操作。关联方法不需要 self 参数。
// www.javascriptcn.com code example
impl Rectangle {
// 关联方法
fn square(size: u32) -> Rectangle {
Rectangle { width: size, height: size }
}
}
fn main() {
let square = Rectangle::square(10);
println!("Square area: {}", square.area());
}本题详细解读
实例方法
实例方法是通过结构体的实例来调用的,第一个参数通常是 self,表示当前结构体的实例。self 可以是以下几种形式:
&self:表示不可变借用。&mut self:表示可变借用。self:表示获取所有权。
实例方法通常用于对结构体的数据进行操作或查询。
关联方法
关联方法不依赖于结构体的实例,通常用于构造函数或其他不依赖于实例的操作。关联方法不需要 self 参数,通常通过结构体的名称来调用。
关联方法的一个常见用途是实现构造函数,例如 Rectangle::square(size: u32) 方法,它返回一个正方形的 Rectangle 实例。
方法调用语法
在 Rust 中,方法调用使用点号 . 语法。对于关联方法,使用双冒号 :: 语法。
let rect = Rectangle { width: 30, height: 50 };
println!("Area: {}", rect.area()); // 实例方法调用
let square = Rectangle::square(10); // 关联方法调用
println!("Square area: {}", square.area());方法链
Rust 支持方法链,即在一个表达式中连续调用多个方法。
// www.javascriptcn.com code example
impl Rectangle {
fn set_width(&mut self, width: u32) -> &mut Self {
self.width = width;
self
}
fn set_height(&mut self, height: u32) -> &mut Self {
self.height = height;
self
}
}
fn main() {
let mut rect = Rectangle { width: 30, height: 50 };
rect.set_width(40).set_height(60);
println!("Area: {}", rect.area());
}在这个例子中,set_width 和 set_height 方法都返回 &mut Self,允许在同一个表达式中连续调用这两个方法。