Disable default constructor in Rust?

巧了我就是萌 提交于 2020-12-26 05:19:11

问题


Say I define my own type in a Rust library, like so:

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 prohibit users from creating their own Date struct with the default constructor like so:

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

I ask because it seems to be a detrimental flaw if you cannot force developers to run their arguments through a battery of validation before setting the members of a struct. (Although, maybe there is some other pattern that I should use in Rust, like validating data when they are used rather than when they are created; feel free to comment on that.)


回答1:


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

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

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

Note that the same is true of functions, since new is not marked pub here, it's inaccessible to any module other than the current one.



来源:https://stackoverflow.com/questions/45017183/disable-default-constructor-in-rust

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!