MST

星途 面试题库

面试题:Rust结构体中self的常见使用场景

在Rust结构体中,self用于关联方法。请列举至少3种self常见的使用场景,并各给出一段简单的代码示例。
10.5万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

一键面试
  1. 不可变借用 &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);
}
  1. 可变借用 &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);
}
  1. 所有权转移 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);
}