MST
星途 面试题库

面试题:Rust消费顺序在函数参数传递中的体现

在Rust中,当一个函数接收某个类型的参数时,简述参数传递过程中消费顺序的特点,并举例说明。如果传递的是一个自定义结构体,该结构体的成员变量会遵循怎样的消费顺序?
26.9万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

一键面试

参数传递过程中消费顺序特点

在Rust中,当函数接收某个类型的参数时,参数传递遵循“所有权转移”原则。这意味着当参数传递给函数时,调用者会失去对该值的所有权,函数获得所有权。当函数结束时,函数会销毁拥有所有权的值,除非该值被返回给调用者或移动到其他地方。

举例说明

fn consume_string(s: String) {
    println!("Consuming string: {}", s);
}

fn main() {
    let my_string = String::from("Hello, Rust!");
    consume_string(my_string);
    // 下面这行代码会报错,因为my_string的所有权已转移到consume_string函数中
    // println!("Trying to use my_string: {}", my_string); 
}

在上述例子中,my_string 的所有权被转移到 consume_string 函数中,函数结束后 my_string 被销毁。

自定义结构体成员变量的消费顺序

当传递一个自定义结构体时,同样遵循所有权转移原则。结构体整体的所有权转移到函数中,结构体的成员变量也随着结构体一起被转移和消费。例如:

struct MyStruct {
    field1: String,
    field2: i32,
}

fn consume_struct(s: MyStruct) {
    println!("Consuming struct with field1: {}, field2: {}", s.field1, s.field2);
}

fn main() {
    let my_struct = MyStruct {
        field1: String::from("Some text"),
        field2: 42,
    };
    consume_struct(my_struct);
    // 下面这行代码会报错,因为my_struct的所有权已转移到consume_struct函数中
    // println!("Trying to use my_struct: {:?}", my_struct); 
}

在这个例子中,MyStruct 实例 my_struct 的所有权被转移到 consume_struct 函数中,其成员变量 field1String 类型)和 field2i32 类型)也随着结构体一起被转移和消费。当 consume_struct 函数结束时,my_struct 及其成员变量都会被销毁。