Option Fn and type inference for None case

Imo even better than @quinedot’s solution is getting a zero-sized option type (by using an uninhabited function type). You can do something like this:

#[inline]
pub fn nop() -> Option<impl Fn(&mut sidoc::Builder)> {
    enum Void {}
    None::<Void>.map(|void| move |_: &mut sidoc::Builder| match void {})
}
println!("{}", std::mem::size_of_val(&NOP));   // -> 8
println!("{}", std::mem::size_of_val(&nop())); // -> 0

(playground)


Edit 2022: This code will need slight modification to get the same zero-sized option behavior in edition 2021.

5 Likes