如何解构元组以使绑定可变? [英] How do I destructure a tuple so that the bindings are mutable?

查看:28
本文介绍了如何解构元组以使绑定可变?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有以下结构:

struct MyStruct { tuple: (i32, i32) };

还有以下功能:

// This will not compile
fn function(&mut struct: MyStruct) {
    let (val1, val2) = struct.tuple;
    val1 = 1;
    val2 = 2;
}

如何将 val1 和 val2 借用为可变的,以便当我重新分配它们时,更改会出现在原始结构中?

How do I borrow val1 and val2 as mutable so when I reassign them the changes appear in the original struct?

推荐答案

您遇到了一些问题:

  • 你把 &mut 放在了错误的地方;&mut 是类型的一部分,而不是参数(除非你正在解构参数,而你不是).

  • You've put the &mut in the wrong place; &mut is part of the type, not the argument (unless you're destructuring the argument, which you aren't).

你不能调用参数 struct,因为它是一个关键字.

You can't call the argument struct, because that's a keyword.

不能直接赋值给可变引用.

You can't assign to a mutable reference with straight assignment.

因此,考虑到这些,这里有一个可行的解决方案:

So, with those in mind, here's a working solution:

#[derive(Debug)]
struct MyStruct {
    tuple: (i32, i32),
}

fn function(s: &mut MyStruct) {
    let (ref mut val1, ref mut val2) = s.tuple;
    *val1 = 1;
    *val2 = 2;
}

fn main() {
    let mut s = MyStruct { tuple: (0, 0) };
    function(&mut s);
    println!("{:?}", s);
}

这里的关键是模式中的ref是通过引用绑定的;将它与 mut 结合起来为您提供可变引用.具体来说,它为您提供了一对 &mut i32 .由于这些是引用,您必须取消引用它们才能通过它们分配(否则,您将尝试重新分配引用本身).

The key here is that ref in a pattern binds by-reference; combining that with mut gives you a mutable reference. Specifically, it gives you a pair of &mut i32s. Since these are references, you have to de-reference them in order to assign through them (otherwise, you'd be trying to re-assign the reference itself).

这篇关于如何解构元组以使绑定可变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆