How to keep a random-size byte array in a Rust struct?

Viewed 34

I'm trying to do this, but it doesn't work:

struct Pack {
  data: Box<[u8]>
}
fn foo() {
  let mut p = Pack {
    data: Box::new(**b"Hello!")
  };
  p.data.set(b"Bye!");
}

I'm getting:

error[E0614]: type `[u8; 6]` cannot be dereferenced
  --> foo
   |
30 |         data: Box::new(**b"Hello!")
   |                        ^^^^^^^^^^^

error[E0277]: the size for values of type `[u8]` cannot be known at compilation time
   --> foo
    |
30  |         data: Box::new(**b"Hello!")
    |               ^^^^^^^^ doesn't have a size known at compile-time
    |

What is the right way to do this?

1 Answers

Just use a Vec instead:

struct Pack {
  data: Vec<u8>
}
fn foo() {
  let mut p = Pack {
    data: b"Hello!".to_vec()
  };
  p.data=b"Bye!".to_vec();
}

A vector is just like a array, except it's size is dynamic and you can resize it at runtime. See the docs for more details.

Related