Tuple constructors

Why are tuple-like structs/enums's constructors treated as functions?
example:

fn main() {
    let foo = [1, 2, 3].map(Some); // map expects a closure but I can also pass Option::Some here
    dbg!(foo); // prints [Some(1), Some(2), Some(3)]
}

example 2:

use std::num::NonZero;

struct Foo(NonZero<u32>);
impl Foo {
    fn try_new(n: u32) -> Option<Self> {
        // Self here is a struct but I can pass it to Option::map, which again expects a closure
        NonZero::new(n).map(Self)
    }
}

Also, apparently this doesn't work with structs using named fields or enums variants that have named fields.

because they are functions. the tuple structs section of the reference says:

... In addition to defining a type, it also defines a constructor of the same name in the value namespace. The constructor is a function which can be called to create a new instance of the struct.

1 Like