'Why does Option<NonZeroU32> not require using explicit Some?

I have noticed by accident that the following code compiles and works, but I am curious why? I understand why Option of u32 requires an explicit Some, but I don't understand why NonZeroU32 is special and actually forbids from explicitly using Some.

use std::num::NonZeroU32;

fn main() {
    let x : Option<u32> = Some(1);
    //let y : Option<NonZeroU32> = Some(NonZeroU32::new(2)); //doesn't compile
    let y : Option<NonZeroU32> = NonZeroU32::new(2);
    println!("{} {}", x.unwrap(), y.unwrap());
}

I tried looking in https://doc.rust-lang.org/stable/std/num/struct.NonZeroU32.html and https://doc.rust-lang.org/stable/src/core/num/nonzero.rs.html#25-155

I noticed that there is

#[rustc_nonnull_optimization_guaranteed]

and I think this is why explicit Some is not required, but I lack experience to confirm my theory.



Solution 1:[1]

NonZeroU32::new() return None if the argument n is zero. The Option is a failure indicator of the function. It's a very common pattern in Rust and have no relation to rustc_nonnull_optimization_guaranteed

Solution 2:[2]

No, this is because NonZeroU32::new() already returns Option<NonZeroU32> (it returns None if given zero).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Stargateur
Solution 2