为什么 Rust 文档在访问向量元素时使用引用 (&)?

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

我一直在阅读 Rust 文档,特别是有关读取向量元素的部分(清单 8-4)。给出的示例展示了如何使用索引和 get 方法从向量访问元素:

let v = vec![1, 2, 3, 4, 5];

let third: &i32 = &v[2];
println!("The third element is {third}");

let third: Option<&i32> = v.get(2);
match third {
    Some(third) => println!("The third element is {third}"),
    None => println!("There is no third element."),
}

我了解如何访问向量的元素,但我不完全理解为什么文档在访问索引 2 处的元素时使用引用 (&)。

为什么不直接写:

let third = v[2];
println!("The third element is {third}");

在第一个示例中,

let third: &i32 = &v[2];
给出了对元素的引用,但我不清楚为什么他们选择使用引用而不是直接获取不带&的值。这种方法背后的原因是什么?在这种情况下使用引用 (&) 有什么好处吗?

如有任何澄清,我们将不胜感激!

rust vector reference rustdoc
1个回答
0
投票

问题已经在 cdhowie 的评论中得到了解答(为什么 Rust 文档在访问向量元素时使用引用(&)?

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.