您可以禁用类型的构造函数语法吗? [英] Can you disable constructor syntax for a type?

查看:34
本文介绍了您可以禁用类型的构造函数语法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在 Rust 库中定义了自己的类型,如下所示:

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 }
    }
}

有没有办法要求用户使用Date::new构造函数?换句话说,我能否以某种方式禁止用户使用以下构造函数创建他们自己的 Date 结构:

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 };

我这么问是因为如果您不能强制开发人员在设置结构成员之前通过一系列验证来运行他们的参数,这似乎是一个有害缺陷.(虽然,也许我应该在 Rust 中使用其他一些模式,例如在使用数据时验证数据,而不是在创建数据时验证数据;请随时对此发表评论.)

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

推荐答案

TL;DR:默认情况下,默认构造函数"已被禁用.

struct 语法仅适用于那些有权访问 struct所有字段的人.

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

因此,根据隐私规则,它只能在同一模块中访问,除非所有字段都标记为 pub,在这种情况下,它可以在 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.

注意函数也是如此,因为new在这里没有被标记为pub,所以除了当前的任何模块都无法访问它一个.

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.

这篇关于您可以禁用类型的构造函数语法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆