Rust:可以同时获得元组每个元素的可变引用

huangapple go评论49阅读模式
英文:

Rust: Mutable references to each element of a tuple possible at the same time

问题

以下代码可以正常编译,没有任何问题:

fn main() {
    let mut w = (107, 109);
    let w0 = &mut w.0;
    let w1 = &mut w.1;
    *w0 = 110;
    *w1 = 111;
    println!("{}", w0);
    println!("{}", w1);
    println!("{:?}", w);
}

但是下面的代码无法编译,因为现在 w 是一个数组:

fn main() {
    let mut w = [107, 109];
    let w0 = &mut w[0];
    let w1 = &mut w[1];
    *w0 = 110;
    *w1 = 111;
    println!("{}", w0);
    println!("{}", w1);
    println!("{:?}", w);
}

为什么这个情况下它适用于元组?

英文:

Below code compiles without any issues:

fn main() {
    let mut w = (107, 109);
    let w0 = &mut w.0;
    let w1 = &mut w.1;
    *w0 = 110;
    *w1 = 111;
    println!("{}", w0);
    println!("{}", w1);
    println!("{:?}", w);
}

But the following doesn't compile where w is now an array:

fn main() {
    let mut w = [107, 109];
    let w0 = &mut w[0];
    let w1 = &mut w[1];
    *w0 = 110;
    *w1 = 111;
    println!("{}", w0);
    println!("{}", w1);
    println!("{:?}", w);
}

Why is it the case that it works with tuples?

答案1

得分: 4

> 为什么它可以用于元组?

元组是一个匿名结构,即使字段是按位置命名的。因此,编译器理解 w.0w.1 不会重叠,并且能够分离借用

然而,数组是索引的,对编译器而言是不透明的,因此 w[0]w[1] 可能是同一个位置。

英文:

> Why is it the case that it works with tuples?

A tuple is an anonymous structure, even if the fields are named by their position. So the compiler understands that w.0 and w.1 don't overlap and it's able to split the borrow.

Arrays however are indexed, they are opaque to the compiler, for which w[0] and w[1] may well be the same location.

huangapple
  • 本文由 发表于 2023年5月20日 23:38:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/76296016.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定