Rust 类方法参数:self、&self、&mut self 使用详解
在 Rust 语言中,类方法的第一个参数可以是 self、&self 或者 &mut self,具体使用哪种形式取决于方法是否需要修改对象本身。
- 使用 self 作为第一个参数时,该方法会获得对象的所有权,允许方法在执行过程中修改对象的内部状态。使用 self 的方法被称为“拥有者方法”(owned method)。
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(self) -> u32 {
self.width * self.height
}
}
fn main() {
let rect = Rectangle {
width: 10,
height: 20,
};
let area = rect.area();
println!("The area is {}", area);
}
- 使用 &self 作为第一个参数时,该方法会借用对象的不可变引用,允许方法读取对象的内部状态,但不能修改。使用 &self 的方法被称为“共享借用方法”(shared borrowing method)。
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
}
fn main() {
let rect = Rectangle {
width: 10,
height: 20,
};
let area = rect.area();
println!("The area is {}", area);
}
- 使用 &mut self 作为第一个参数时,该方法会借用对象的可变引用,允许方法读取和修改对象的内部状态。使用 &mut self 的方法被称为“可变借用方法”(mutable borrowing method)。
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn increase_size(&mut self, increment: u32) {
self.width += increment;
self.height += increment;
}
}
fn main() {
let mut rect = Rectangle {
width: 10,
height: 20,
};
rect.increase_size(5);
println!("The new width is {}, and the new height is {}", rect.width, rect.height);
}
需要根据方法是否需要修改对象的内部状态来选择使用哪种形式的参数。如果方法只需要读取对象的内部状态,应使用 &self;如果方法需要修改对象的内部状态,应使用 &mut self;如果方法需要获取对象的所有权并可能修改对象的内部状态,应使用 self。
原文地址: https://www.cveoy.top/t/topic/qyCq 著作权归作者所有。请勿转载和采集!