Tuple constructors

⚓ Rust    📅 2025-12-20    👤 surdeus    👁️ 1      

surdeus

Info

This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: 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.

2 posts - 2 participants

Read full topic

🏷️ Rust_feed