为什么我在不使用引用的情况下获得所有权后仍然可以访问向量的元素? [英] Why I can still access a vector's element after taking ownership of it without using reference?

查看:52
本文介绍了为什么我在不使用引用的情况下获得所有权后仍然可以访问向量的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

fn main() {
    let number_list = vec![1, 2, 3, 4, 5];

    let n = number_list[0];
    let r = &number_list[0];

    println!("{} : {} : {} : {}", n, r, number_list[0], &number_list[0]);
}

输出为:

1 : 1 : 1 : 1

另一个问题是,除了引用之外,使用引用和非引用的向量索引有什么区别?

Another question is what is the difference between vector indexing with a reference and a non-reference except taking the reference?

推荐答案

你有一个整数向量 (i32 是特定的),并且 i32 实现了 Copy 特性.

You have a vector of integers (i32 to be specific), and i32 implements the Copy trait.

索引语法返回取消引用的值.由于索引类型实现了Copy,编译器会隐式复制它.

The index syntax returns a dereferenced value. Since the indexed type implements Copy, the compiler copies it implicitly.

根本无法使用索引语法从向量中获取项目的所有权.

带引用的向量索引和不带引用的向量索引有什么区别,但不引用引用

what is the difference between vector indexing with a reference and a non-reference except taking the reference

如果没有 &,值会被复制(但仅仅是因为它实现了 Copy).使用 &,您可以引用向量中的值.

Without the &, the value is copied (but only because it implements Copy). With the &, you have a reference to the value inside the vector.

这篇关于为什么我在不使用引用的情况下获得所有权后仍然可以访问向量的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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