![](/img/trans.png)
[英]How do I convert the “largest value in a Vec” example in the Rust book to not use the Copy trait?
[英]How do I push a value into a 2D Vec in Rust?
這是2D Vec
一個非常簡單的嘗試。 我正在嘗試在頂級Vec
的最后一個條目中添加一個元素:
fn main() {
let mut vec_2d = vec![vec![]];
if let Some(v) = vec_2d.last() {
v.push(1);
}
println!("{:?}", vec_2d);
}
我收到此錯誤:
error[E0596]: cannot borrow `*v` as mutable, as it is behind a `&` reference
--> src/main.rs:4:9
|
3 | if let Some(v) = vec_2d.last() {
| - help: consider changing this to be a mutable reference: `&mut std::vec::Vec<i32>`
4 | v.push(1);
| ^ `v` is a `&` reference, so the data it refers to cannot be borrowed as mutable
我也試過Some(ref v)
和Some(ref mut v)
,結果相同。 我找不到任何具體描述此錯誤的文檔。 這里的正確方法是什么?
對類似問題的回答建議更像Some(&mut v)
。 然后我得到這些錯誤:
error[E0308]: mismatched types
--> src/main.rs:3:17
|
3 | if let Some(&mut v) = vec_2d.last() {
| ^^^^^^ types differ in mutability
|
= note: expected type `&std::vec::Vec<_>`
found type `&mut _`
= help: did you mean `mut v: &&std::vec::Vec<_>`?
如果我嘗試Some(&ref mut v)
我得到:
error[E0596]: cannot borrow data in a `&` reference as mutable
--> src/main.rs:3:18
|
3 | if let Some(&ref mut v) = vec_2d.last() {
| ^^^^^^^^^ cannot borrow as mutable
使用last_mut
對最后一個元素的可變引用; 無需改變模式。
fn main() {
let mut vec_2d = vec![vec![]];
if let Some(v) = vec_2d.last_mut() {
v.push(1);
}
println!("{:?}", vec_2d);
}
針對這種特殊情況的(更)更優雅的解決方案是:
fn main() {
let vec_2d = vec![vec![1i32]];
println!("{:?}", vec_2d);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.