在Rust语言中,类方法的第一个参数可以是self、&self或者&mut self,具体使用哪种形式取决于方法是否需要修改对象本身。

  1. 使用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);
}
  1. 使用&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);
}
  1. 使用&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

rust语言中的类方法的第一个参数什么时候使用self什么时候用&self

原文地址: http://www.cveoy.top/t/topic/iSDH 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录