为什么我可以隐藏之前借用过的变量?楼主在哪里?

问题描述 投票:0回答:2

试图理解 Rust 中的所有权和借用,我遇到了这种情况,我创建了一个对象

a
(应该是所有者),然后将其借入
b
。然后,我尝试遮蔽
a

#[derive(Debug)]
struct Struct1;

#[derive(Debug)]
struct Struct2;

fn main() {
    let a = Struct1;
    let b = &a;

    let a = Struct2;
    
    println!("{:?} {:?}", a, b);
}

问题是,我预计这会失败,但实际上它确实有效,输出为:

Struct2 Struct1

如果我影子

a
,借来的
b
的主人在哪里?

rust borrow-checker ownership shadowing ownership-semantics
2个回答
0
投票

第一个

a
仍然是
Struct1
的所有者,其生命周期直到 main 中最后一次使用为止,即当
b
println!
之后被删除时借用结束。阴影创建一个新的绑定,除了使其在当前范围内不可见之外,不会影响前一个绑定。

因此,这个程序相当于(并且只是语法糖)一个程序:

#[derive(Debug)]
struct Struct1;

#[derive(Debug)]
struct Struct2;

fn main() {
    let a_1 = Struct1;
    let b = &a_1;

    let a_2 = Struct2;
    
    println!("{:?} {:?}", a_2, b);
}

其中

a_1
a_2
绑定后不直接交互。


0
投票

Struct1
的所有者仍然是您创建的第一个
a
变量。事实上,您声明了另一个具有相同名称的变量,这在所有权方面不会产生任何影响,它只会在语法级别产生影响,因为从那时起
a
将引用其他内容。

© www.soinside.com 2019 - 2024. All rights reserved.