Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading