如何使用 `index_mut` 来获取可变引用? [英] How can I use `index_mut` to get a mutable reference?

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

问题描述

即使我为我的结构实现了 IndexMut,我也无法获得对结构内部向量元素的可变引用.

Even when I implement IndexMut for my struct, I cannot get a mutable reference to an element of structure inner vector.

use std::ops::{Index, IndexMut};

struct Test<T> {
    data: Vec<T>,
}

impl<T> Index<usize> for Test<T> {
    type Output = T;
    fn index<'a>(&'a self, idx: usize) -> &'a T {
        return &self.data[idx];
    }
}

impl<T> IndexMut<usize> for Test<T> {
    fn index_mut<'a>(&'a mut self, idx: usize) -> &'a mut T {
        // even here I cannot get mutable reference to self.data[idx]
        return self.data.index_mut(idx);
    }
}

fn main() {
    let mut a: Test<i32> = Test { data: Vec::new() };
    a.data.push(1);
    a.data.push(2);
    a.data.push(3);
    let mut b = a[1];
    b = 10;

    // will print `[1, 2, 3]` instead of [1, 10, 3]
    println!("[{}, {}, {}]", a.data[0], a.data[1], a.data[2]);
}

如何使用 index_mut 获取可变引用?可能吗?

How can I use index_mut to get a mutable reference? Is it possible?

推荐答案

大功告成.改变这个:

let mut b = a[1];
b = 10;

为此:

let b = &mut a[1];
*b = 10;

索引语法返回值本身,而不是对它的引用.您的代码从您的向量中提取一个 i32 并修改变量 - 自然,它不会影响向量本身.为了通过索引获取引用,需要显式写.

Indexing syntax returns the value itself, not a reference to it. Your code extracts one i32 from your vector and modifies the variable - naturally, it does not affect the vector itself. In order to obtain a reference through the index, you need to write it explicitly.

这是相当自然的:当您使用索引访问切片或数组的元素时,您获得的是元素的值,而不是对它们的引用,为了获得引用,您需要明确地编写它.

This is fairly natural: when you use indexing to access elements of a slice or an array, you get the values of the elements, not references to them, and in order to get a reference you need to write it explicitly.

这篇关于如何使用 `index_mut` 来获取可变引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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