Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the implications of using Vec<T> over Option<Vec<T>>?

Tags:

rust

I am creating a lot of structs using Option<Vec<T>> instead of Vec<T> to not allocate memory when not needed. And I looked up this answer about the sizes of both Vec & Option<Vec>> and both were same.

So my question is this. Should I use Vec<T> and check its .len() for the same effect or continue using Option? Or are they equivalent?

Also originally I am a JavaScript Developer. And getting paranoid over to allocate or not to allocate.

like image 813
pepsighan Avatar asked Dec 11 '22 07:12

pepsighan


1 Answers

An empty Vec doesn't allocate, because there's nothing for it to store.

The two are the same size because of an optimisation the compiler uses, but this has no bearing on what the types mean. Even with this optimisation, an empty Vec and None aren't the same thing. One indicates the presence of an empty Vec, the other indicates the absence of any Vec at all. Depending on what exactly you're doing, the distinction could be important.

like image 142
DK. Avatar answered Feb 01 '23 12:02

DK.