- 不可变借用
&self
:常用于读取结构体内部数据而不修改它的方法。
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
}
fn main() {
let rect = Rectangle { width: 10, height: 5 };
let area = rect.area();
println!("The area of the rectangle is: {}", area);
}
- 可变借用
&mut self
:当需要修改结构体内部数据时使用。
struct Counter {
count: u32,
}
impl Counter {
fn increment(&mut self) {
self.count += 1;
}
fn get_count(&self) -> u32 {
self.count
}
}
fn main() {
let mut counter = Counter { count: 0 };
counter.increment();
let count = counter.get_count();
println!("The count is: {}", count);
}
- 所有权转移
self
:当方法需要接管结构体的所有权,可能用于消耗结构体实例并返回某些值的场景。
struct StringHolder {
data: String,
}
impl StringHolder {
fn into_string(self) -> String {
self.data
}
}
fn main() {
let holder = StringHolder { data: String::from("Hello") };
let s = holder.into_string();
println!("Got string: {}", s);
}