'How to restrict the construction of struct?

Is it possible to forbid creating an instances directly from member initialization?

e.g.

pub struct Person {
    name: String,
    age: u8,
}

impl Person {
    pub fn new(age: u8, name: String) -> Person {
        if age < 18 {
            panic!("Can not create instance");
        }
        Person { age, name }
    }
}

I can still use Person {age: 6, name:String::from("mike")} to create instance. Is there anyway to avoid this?



Solution 1:[1]

For Rust >= 1.40.0, consider applying the non_exhaustive attribute to your struct.

// Callers from outside my crate can't directly construct me
// or exhaustively match on my fields!
#[non_exhaustive]
pub struct Settings {
  pub smarf: i32,
  pub narf: i32,
}

More info in the 1.40.0 release notes.

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 KittenOverflow