1

My function might fail, but it doesn't return result, the empty type in rust is () as such takes up 0 bytes, if Option is defined like that

pub enum Option<T> {
    None,
    Some(T),
}

It shouldn't have overhead (on return) at all, because the tag only takes up 1 byte, just like the boolean. Is that correct? Upon inspecting Compiler Explorer disassembly output I found out that they produce exactly the same code, but I still wonder if that is correct for all cases, is there cases where returning empty option might have an overhead?

The convenience of Option<()> over bool is unwrapping and handling functions

Just in case my function that returns empty option will be called a lot.

  • 7
    I would find something that returned `Option<()>` a bit odd. If something can fail, I'd expect a `Result<(), SomeError>`. `SomeError` can be a unit or empty struct and it'd still be the same as a bool under the hood. – kmdreko Dec 05 '20 at 18:51
  • I believe `Result<(), ()>` fits a little bit better. – MaxV Dec 05 '20 at 19:12
  • 1
    [Null pointer optimization](https://stackoverflow.com/questions/46557608/what-is-the-null-pointer-optimization-in-rust) – Mihir Luthra Dec 06 '20 at 01:35

0 Answers0