Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
953 views
in Technique[技术] by (71.8m points)

rust - Can you disable constructor syntax for a type?

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 using the following constructor:

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.)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...