[Solved] How does one declare a &mut std::vec::Vec<u8>?

I'm getting my feet wet with Rust, so I think I'm in that early phase where I'm still fighting with the borrow checker.

I have the following code that I'm using to load up a buffer:

pub fn append_data(&mut self, buffer: &mut Vec<u8>, data: Vec<u8>) {
    for byte in data.iter() {
        buffer.push(*byte);
    }
}

pub fn make_control_packet(&mut self, data: Vec<u8>, buffer: &mut Vec<u8>) {

    let mut packet: Vec<u8> = vec![];
    self.append_data(&packet, vec![1,2,3]);
}

However, the compiler is telling me I need to make a "mut std::vec::Vec" and pass the reference to that:

error[E0308]: mismatched types
  --> src\controller.rs:74:26
   |
74 |         self.append_data(&packet, vec![1,2,3]);
   |                          ^^^^^^^ types differ in mutability
   |
   = note: expected type `&mut std::vec::Vec<u8>`
   = note:    found type `&std::vec::Vec<u8>`

error: aborting due to previous error

However, I can't seem to find a combination of tokens to declare a "mut std::vec::Vec". For example, I would have thought " let mut packet: mut Vec = vec!;" or "let mut packet: mut std::vec::Vec = Vec::new()" would work, but I can't get the compiler to accept any variant thereof.

I think this should do it:

self.append_data(&mut packet, vec![1,2,3]);
1 Like

Try:

self.append_data(&mut packet, vec![1,2,3]);
1 Like

That solves the problem. Thank you very much for the help.

I haven't seen that syntax anywhere, and can't find it in the Rust Book. Is it new syntax, or is it just not very common?

It's briefly described in the References and Borrowing chapter and also appears quite often in the Mutability chapter. It's a really common syntax in Rust – it's just a mutable analogue of & operator.

1 Like

Did you try: self.append_data(&mut packet, vec![1,2,3]); ?

Declaring the vec as mutable just means you're allowing mutation to it - as an owner of it, you can mutate it. "&mut" is asking for a mutable borrow to be taken. So slightly different things.

1 Like