Disable default constructor in Rust?

Let's say I define my own type in the Rust library, for example:

struct Date { year: u16, month: u8, day: u8 } impl Date { fn new(y: u16, m: u8, d: u8) -> Date { // Do some validation here first Date { year: y, month: m, day: d } } } 

Is there a way to require users to use the Date::new constructor? In other words, can I somehow prevent users from creating their own Date structure with a standard constructor like this:

 let d = Date { 2017, 7, 10 }; 

I ask because this seems like a harmful flaw if you cannot get developers to run their arguments with a validation battery before setting members to the structure. (Although maybe there is another template that I should use in Rust, for example, checking the data when it is used, and not when it is created, feel free to comment on this.)

+8
rust
source share
1 answer

TL; DR: "Default constructor" is already disabled by default.

The syntax struct is available only to those who have access to all fields of the struct .

As a result, it is available only in the same module as the privacy rules, unless all the fields are marked with pub , in which case it is available wherever the struct is located.

Please note that the same applies to functions, since new is not marked pub , it is not available for any other module except the current one.

+9
source share

All Articles