容器的成员是否继承其可变性? [英] Do a container's members inherit its mutability?

查看:46
本文介绍了容器的成员是否继承其可变性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

像这样编译并运行良好:

Something like this compiles and runs fine:

#[derive(Clone)]
struct Member {
    x: i32,
}

fn main() {
    let mut arr = vec![Member { x: 5 }; 5];

    arr[0].x = 25;

    println!("{}", arr[0].x); // Gives 25
}

是否因为如果对容器(例如 Vec)的引用是可变的,那么它的元素继承"了它的可变性?

Is it because if a reference to a container such as Vec is made mutable, then its elements "inherit" its mutability?

推荐答案

一般来说,可变性是由类型的字段继承"的,这取决于变量的绑定.来自Rust 编程语言定义结构的章节:

In general, mutability is "inherited" by the fields of a type depending on the binding of the variable. From The Rust Programming Language's chapter on defining structs:

如果实例是可变的,我们可以通过使用点来改变一个值符号并分配到特定字段

If the instance is mutable, we can change a value by using the dot notation and assigning into a particular field

[...]

注意整个实例必须是可变的

Note that the entire instance must be mutable

然而,这不是这里发生的事情.正如Veedrac 在评论中指出的,您没有访问容器的字段,但您正在调用一个方法.

However, that's not what's happening here. As Veedrac points out in the comments, you aren't accessing the fields of the container, but you are calling a method.

[] 操作符由 IndexMut 特性:

The [] operator is powered by the IndexMut trait:

pub trait IndexMut<Idx>: Index<Idx>
where
    Idx: ?Sized,
{
    fn index_mut(&mut self, index: Idx) -> &mut Self::Output;
}

您的代码转换为类似于:

Your code translates to something akin to:

{
    let tmp: &mut Member = IndexMut::index_mut(&mut arr, 0);
    tmp.x = 25;
}

在这种情况下,没有什么是继承的",它是通过方法实现明确授予的.

In this case, nothing is "inherited", it's explicitly granted via the method implementations.

另见:

这篇关于容器的成员是否继承其可变性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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