MST

星途 面试题库

面试题:Rust中嵌套函数的作用域基本规则

在Rust中,简述嵌套函数的作用域范围是如何界定的?外部函数的变量在嵌套函数中访问规则是怎样的?请举例说明。
49.7万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

一键面试

嵌套函数作用域范围界定

在Rust中,嵌套函数的作用域被限定在其外部函数内部。它不能在外部函数之外被调用或访问。例如:

fn outer_function() {
    fn inner_function() {
        println!("This is the inner function.");
    }
    inner_function();
}
// inner_function();  // 这里会报错,因为inner_function作用域仅限于outer_function内部

外部函数变量在嵌套函数中的访问规则

  1. 不可变借用:嵌套函数可以不可变借用外部函数的变量。例如:
fn outer() {
    let x = 10;
    fn inner() {
        println!("x from outer: {}", x);
    }
    inner();
}
  1. 可变借用:如果需要可变借用外部函数变量,外部变量必须声明为mut,并且在同一作用域内不能有不可变借用。例如:
fn outer() {
    let mut x = 10;
    fn inner() {
        x += 1;
        println!("x from outer: {}", x);
    }
    inner();
}
  1. 所有权转移:嵌套函数也可以获取外部函数变量的所有权。例如:
fn outer() {
    let s = String::from("hello");
    fn inner(s: String) {
        println!("s from outer: {}", s);
    }
    inner(s);
}

在上述例子中,s的所有权被转移到了inner函数中。