简体   繁体   English

Rust 禁用结构构造

[英]Rust disable struct construction

How can I disable struct construction but maintaining pattern matching in Rust?如何在 Rust 中禁用结构构造但保持模式匹配?

Let's see an example:让我们看一个例子:

struct OrderedPair(pub u32, pub u32);

impl OrderedPair {
    fn new(a: u32, b: u32) -> Self {
        if a < b {
            Self(a, b)
        } else {
            Self(b, a)
        }
    }
}

It's obvious that I want to inhibit the construction of such struct (eg OrderedPair(2, 1) ) and to use only the new method, in order to preserve the invariant.很明显,我想禁止构建这种结构(例如OrderedPair(2, 1) )并只使用new方法,以保持不变性。 I know of 3 ways to do this:我知道 3 种方法可以做到这一点:

  1. Make private the fields将字段设为私有
struct OrderedPair(u32, u32);
  1. Add a private dummy field添加私有虚拟字段
struct OrderedPair(pub u32, pub u32, ());
  1. Make the struct non-exhaustive使结构不详尽
#[non_exhaustive]
struct OrderedPair(pub u32, pub u32);

The issues are that with 1 I cannot access the members at all and with all three I cannot use pattern matching问题是 1 我根本无法访问成员,而所有三个我都无法使用模式匹配

let OrderedPair(min, max) = my_ordered_pair;

So is there a way to block struct construction but allow pattern matching?那么有没有办法阻止结构构造但允许模式匹配?

I know that if we declare a mutable variable of that type with public access to members then the invariant can be broken by manually changing the members, but for now avoiding the struct constructor is enough.我知道,如果我们声明一个具有对成员的公共访问权限的该类型的可变变量,那么可以通过手动更改成员来破坏不变量,但现在避免使用 struct 构造函数就足够了。

Instead of doing pattern matching directly on the fields, you can do it on a returned tupple:您可以在返回的元组上进行,而不是直接在字段上进行模式匹配:

#[derive(Clone, Copy)]
pub struct OrderedPair {
    a: u32,
    b: u32,
}
impl OrderedPair {
    pub fn content(self) -> (u32, u32) {
        (self.a, self.b)
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM