What is the difference between Vec <struct> and & [struct]?

I often get an error like this:

mismatched types: expected `collections::vec::Vec<u8>`, found `&[u8]` (expected struct collections::vec::Vec, found &-ptr) 

As far as I know, one of them is changed, and the other is not, but I have no idea how to go between types, i.e. take &[u8] and make it Vec<u8> or vice versa.

What is the difference between the two? Is it the same as String and &str ?

+5
source share
1 answer

Is it the same as String and &str ?

Yes. A Vec<T> is its own version of a &[T] . &[T] is a reference to a set of T laid out sequentially in memory (aka. Slice). It is a pointer to the beginning of the elements and the number of elements. The link refers to what you don’t have, so the set of actions you can do with it is limited. There is a modified version ( &mut [T] ) that allows you to mutate elements in a slice. However, you cannot change the number of participants. On the other hand, you cannot mutate the slice itself.

take a &[u8] and make it Vec

In this particular case:

 let s: &[u8]; // Set this somewhere Vec::from(s); 

However, this should allocate memory not on the stack, and then copy each value to this memory. It is more expensive than otherwise, but it may be right for a particular situation.

or vice versa

 let v = vec![1u8, 2, 3]; let s = v.as_slice(); 

This is basically β€œfree” since v still owns the data, we just pass the link to it. This is why many APIs try to use slicers when it makes sense.

+5
source

Source: https://habr.com/ru/post/1209483/


All Articles