Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I determine the zero value of generic types?

Tags:

rust

The closest I managed to find was the std::num::Int and std::num::Float traits, which define zero(). However, they are specific to primitive types.

like image 342
urubi Avatar asked Feb 03 '15 07:02

urubi


Video Answer


1 Answers

No, because it doesn't make sense in general. In fact, there are several types where "zero" is very specifically not valid at all. For example, if you were to take an appropriately-sized zero value and transmute it into a Box, that would violate memory safety!

There's an alternative to "zero", which is the Default trait. It allows you to say Default::default() to get a type's "default" value, whatever that happens to be. However, there's no consistent, sensible definition of "default" for all types. As such, you can only use it for types which explicitly implement it.

like image 145
DK. Avatar answered Sep 27 '22 23:09

DK.