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.)
rust
Jonathan wilbur
source share