How do I create a 2D Vec in Rust?

2019-02-18 12:21发布

问题:

Here is a really simple attempt at a 2D Vec. I'm trying to add an element to the last entry in the top-level Vec:

fn main() {
    let mut _2d = Vec::new();
    _2d.push(Vec::new());
    match _2d.last() {
        Some(v) => v.push(1i),
        None => ()
    }
    println!("{}", _2d);
}

I get this error (using rustc 0.12.0-pre-nightly (cf1381c1d 2014-07-26 00:46:16 +0000)):

test.rs:6:20: 6:21 error: cannot borrow immutable dereference of `&`-pointer `*v` as mutable
test.rs:6         Some(v) => v.push(1i),

I've also tried Some(ref v) and Some(ref mut v) with the same results. I can't find any documentation that describes this error specifically. What is the right approach here?


Edit: An answer to a similar question recommends something more like Some(&mut v). Then I get these errors:

test.rs:6:14: 6:20 error: cannot move out of dereference of `&`-pointer
test.rs:6         Some(&mut v) => v.push(1i),
                       ^~~~~~
test.rs:6:15: 6:20 note: attempting to move value to here (to prevent the move, use `ref v` or `ref mut v` to capture value by reference)
test.rs:6         Some(&mut v) => v.push(1i),

If I further try Some(&ref mut v) I get:

test.rs:6:15: 6:24 error: cannot borrow immutable dereference of `&`-pointer as mutable
test.rs:6         Some(&ref mut v) => v.push(1i),

Edit 2: The results are identical on the latest build from rustup (rustc 0.12.0-pre-nightly (25741603f 2014-08-03 23:46:10 +0000))

回答1:

Just grab a mutable reference to the last element with last_mut; no need to change patterns.

fn main() {
    let mut _2d = Vec::new();
    _2d.push(Vec::new());
    match _2d.last_mut() {
        Some(v) => v.push(1),
        None => ()
    }
    println!("{:?}", _2d);
}


回答2:

A (much) more elegant solution for this particular case would be:

fn main() {
    let _2d = vec![
       vec![1i32]
    ];

    println!("{:?}", _2d);
}