为什么我不能重新绑定引用变量,但我可以重新绑定结构中的引用字段?

似乎我无法在 rust 中重新绑定参考变量

let mut arr = [1, 2, 3, 4]; 
                            
let & mut a0 = & mut arr[0];
println!("a0 = {}", a0);    
                            
let mut i = 0;              
a0 = &mut i; // mismatched types: expected integer, found `&mut {integer}`

但我可以在里面重新绑定一个引用struct

#[derive(Debug)]   
struct Ref<'a, T> {
    val: &'a T     
}                  

let mut arr = [1, 2, 3, 4];

let mut r = Ref {                                          
    val: & arr[0]                                          
};                                                         
println!("r = {:#?}", r);                                  
r.val = & arr[1];                                          

我不能重新绑定引用变量是真的吗?

如果它不能,那么为什么struct像 C++ 一样允许它而不是禁止它?

顺便说一句,Ref<'a, T>在我的代码中是否有与此处相同的标准库类型?

回答

当你写

let & mut a0 = & mut arr[0];

你在这个 let 赋值中使用模式匹配:

& mut {}是图案。如果你替换{},你会得到a0匹配arr[0]

的类型arr[0]usize这样你定义一个a0类型的变量usize

这就是为什么以后不能输入 type 值的原因&mut usize

如果你想a0成为一个类型&mut usize,做

let mut a0 = &mut arr[0];

然后你可以稍后做

let mut i = 0;              
a0 = &mut i;

  • @JiaHaoXu When you wrote `let & mut a0 = & mut arr[0];` I guess you meant `let a0: &mut i32 = & mut arr[0];` (you would also have had to insert `mut` before `a0` to allow reassignment afterwards). In Rust you specify the type after `:`. Your formulation is pattern matching because, in a `let` statement, Rust tries to make both sides of the `=` symbol match. Here `&mut` match perfectly on both sides, then the new name `a0` is associated with `arr[0]` wich is an integer. In the end, `ao` is an integer, not a mutable reference to an integer.
  • @JiaHaoXu The link explicitly says that the left-hand side of `let` assignment is a pattern, and goes on to show examples of destructuring using the pattern, such as `let (x, y, z) = (...)`. The `print_coordinates()` example further demonstrates dereferencing using patterns in function parameters.

以上是为什么我不能重新绑定引用变量,但我可以重新绑定结构中的引用字段?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>