小编Rij*_*jul的帖子

矢量索引时是什么操作(不带&)

根据 rust book(矢量部分 - Ch-8.1)

let mut v = vec![1, 2, 3, 4, 5];
let first = &v[0]; // <-- This is an immutable borrow
v.push(6); // Which is why push() operation is not allowed (since this is a mutable borrow)
println!("The first element is: {}", first);
Run Code Online (Sandbox Code Playgroud)

因为&v[0]是不可变的借用,所以v.push(100)操作不应该起作用。这是有道理的。

然而,这有效:

let mut v = vec![1, 2, 3, 4, 5];
let first = v[0];
v.push(6);
println!("The first element is: {}", first);
Run Code Online (Sandbox Code Playgroud)

&从 中删除时v[0]push() …

rust

5
推荐指数
1
解决办法
554
查看次数

标签 统计

rust ×1