Tuple constructors
⚓ Rust 📅 2025-12-20 👤 surdeus 👁️ 1Why 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
🏷️ Rust_feed