You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rust中Vector的Index trait疑问:为何v[a]是i32而非&i32?

Why is v[a] of type i32 instead of &i32 when using the Index trait?

Great question! Let’s break this down clearly:

First, you’re absolutely right that the Index trait’s index method returns a &T reference. Here’s a simplified look at the trait definition to confirm:

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

So why does v[a] give you an i32 instead of &i32? It comes down to two core Rust behaviors working together:

1. The Copy trait enables seamless value copying

Primitive types like i32, u8, and bool implement the Copy trait. This means when you have a reference to one of these types (like &i32), Rust can automatically create a copy of the underlying value whenever you need to use it as an owned value.

When you write:

let v = vec![1, 2, 3];
let val = v[0]; // val is i32, not &i32

This is equivalent to explicitly writing:

let val = *v.index(0); // Explicit dereference + copy

Since i32 is small and stored entirely on the stack, copying it is extremely fast—Rust does this automatically to keep your code clean and intuitive.

2. This isn’t a "hidden conversion"—it’s intentional ownership behavior

This isn’t an arbitrary implicit rule. If you work with a type that doesn’t implement Copy (like String), you’ll immediately see the reference type:

let v = vec!["hello".to_string(), "world".to_string()];
let s = v[0]; // Error: cannot move out of index of `Vec<String>`
// Because v[0] is &String, and String isn’t Copy—you can’t move from a reference

In this case, you’d have to take a reference (let s = &v[0];), clone the value (let s = v[0].clone();), or use other ownership-safe patterns.

Want to get the reference explicitly?

If you need the &i32 instead of the owned i32, just take a reference to the indexed value:

let v = vec![1, 2, 3];
let val_ref = &v[0]; // val_ref is &i32

To sum up: Rust automatically dereferences and copies Copy types when you use v[a] as an owned value, giving you i32 instead of &i32. This is a deliberate design choice to make working with small, copyable values feel natural while upholding Rust’s strict ownership rules.

内容的提问来源于stack exchange,提问作者ccQpein

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:42:14