如何在 Rust 中返回一个自动取消引用的引用

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

假设我有结构:

struct Vector {
    data: [f32; 2]
}

实现 Index trait 很简单:

impl IndexMut<usize> for Vector {
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        &mut self.data[index]
    }
}

我也有这个实现:

impl Vector {
    fn x(&mut self) -> &mut T {
        &mut self.data[0]
    }
    fn y....
}

技术上我可以做到,但每次我想实际设置 x() 的值时,我需要取消引用它:

*v.x() = 7
有效,但我希望
v.x() = 7
也有效。

当我尝试第二个时,我得到错误:

consider dereferencing here to assign to the mutably borrowed value: '*'
,我想这是有道理的,但它的发生很奇怪,因为 IndexMut 返回与我的 x() 函数返回相同的可变引用。

所以我的问题是:为什么 IndexMut trait 只做

v[0] = 7
,但我的函数需要在使用该值之前取消引用,我应该怎么做(如果可能的话)?

rust indexing struct reference traits
1个回答
2
投票

v[0] = 7
不需要取消引用,因为
v[0]
*v.index(0)
*v.index_mut(0)
的语法糖,具体取决于它的使用方式*,即编译器会在您使用索引语法的任何地方自动插入取消引用,这是大概这样做了,索引的工作方式与其他语言相同,并且更容易使用。

据我所知,您自己的方法无法获得相同的行为。


*正如您从

Index
IndexMut

的文档中看到的那样
© www.soinside.com 2019 - 2024. All rights reserved.