Hacker News new | ask | show | jobs
by typon 3378 days ago
Does anyone know what kind of assembly is generated when using std::option in Rust when make a similar function call?
2 comments

  void f(std::variant<int, char>)
would be

  f(x: IntOrChar)
roughly in Rust, I'm too lazy to make the types _exactly_ the same, but https://godbolt.org/g/pZde2A is roughly it.

Actually, https://godbolt.org/g/1vcMeG might be even better to compare; I'm not an expert, but looks like the only difference is in the size.

last one, adding inline(never) so you can see the calls in main: https://godbolt.org/g/cVDjQH

  movabs  rdi, 21474836480
  call    example::f1@PLT
vs

  mov     edi, 5
  pop     rbp
  jmp     example::f2@PLT
so, yup.
Thank you! This is really cool.
Another cool feature, on top of steveklabnik's comment: rustc is actually smart enough to collapse `Option<T>` where `T` is a borrowed reference (pointer) to a single word. Basically, the compiler knows that the pointer can never be null (borrows are always valid when in scope), so it can use the non-null values for `Some(...)` and the null value for `None`.

In other words, the compiler can turn an Option into a null-pointer convention by reasoning from first principles.

(I think this optimization works for enums in general, and is somehow related to the `nonzero::NonZero` type, but I could be wrong about that.)

Example (look at the calls to f1 and f2 in example::main): https://godbolt.org/g/SSs6X2

Yes. It's when the type is NonZero.