Disable default constructor in Rust?

后端 未结 1 498
失恋的感觉
失恋的感觉 2021-01-17 08:30

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)          


        
1条回答
  •  粉色の甜心
    2021-01-17 09:23

    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.

    0 讨论(0)
提交回复
热议问题