MST
星途 面试题库

面试题:Rust 中结构体可变性控制基础

在 Rust 中,如何定义一个可变的结构体实例?请举例说明。如果有一个结构体包含多个字段,怎样只让其中一个字段可变,而其他字段不可变?
35.8万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

一键面试
  1. 定义一个可变的结构体实例: 在 Rust 中,通过在定义结构体实例时使用 mut 关键字来定义可变的结构体实例。例如:
    struct Point {
        x: i32,
        y: i32,
    }
    
    fn main() {
        let mut p = Point { x: 10, y: 20 };
        p.x = 30;
        println!("p.x: {}, p.y: {}", p.x, p.y);
    }
    
  2. 让结构体中只有一个字段可变,其他字段不可变: 可以使用 CellRefCell 来实现。Cell 适用于简单类型,RefCell 适用于更复杂的类型和需要借用检查的场景。以下是使用 Cell 的例子:
    use std::cell::Cell;
    
    struct Example {
        immutable_field: i32,
        mutable_field: Cell<i32>,
    }
    
    fn main() {
        let ex = Example {
            immutable_field: 10,
            mutable_field: Cell::new(20),
        };
        ex.mutable_field.set(30);
        let value = ex.mutable_field.get();
        println!("immutable_field: {}, mutable_field: {}", ex.immutable_field, value);
    }
    
    如果结构体中的字段类型实现了 Copy 语义,使用 Cell 就足够了。如果字段类型没有实现 Copy 语义,比如 String 类型,就需要使用 RefCell,示例如下:
    use std::cell::RefCell;
    
    struct Example2 {
        immutable_field: i32,
        mutable_field: RefCell<String>,
    }
    
    fn main() {
        let ex2 = Example2 {
            immutable_field: 10,
            mutable_field: RefCell::new(String::from("initial")),
        };
        let mut s = ex2.mutable_field.borrow_mut();
        *s = String::from("changed");
        drop(s);
        let s = ex2.mutable_field.borrow();
        println!("immutable_field: {}, mutable_field: {}", ex2.immutable_field, s);
    }