In Rust, references can never be null, so in case where you actually need null, such as a linked list, you use the Option
type:
struct Element {
value: i32,
next: Option<Box<Element>>,
}
How much overhead is involved in this in terms of memory allocation and steps to dereference compared to a simple pointer? Is there some "magic" in the compiler/runtime to make Option
cost-free, or less costly than if one were to implement Option
by oneself in a non-core library using the same enum
construct, or by wrapping the pointer in a vector?
Yes, there is some compiler magic that optimises
Option<ptr>
to a single pointer (most of the time).The following sizes are printed (on a 64-bit machine, so pointers are 8 bytes):
Note that
&i32
,Box
,&[i32]
,Vec<i32>
all use the non-nullable pointer optimization inside anOption
!This answer is now obsolete; the discriminant in
Option<T>
is now optimised out where possible. (The rest of the information provided is still interesting, though.)For now, an
Option
type occupies the same amount of space than any otherenum
type. I don't know the specifics, but it certainly is represented as some sort of discriminated union.The possibility to tweak the internal representation for optimization is being considered by the Rust developpers.
Here is a relevant discussion on the dev mailing list, posted by Patrick Walton :