Rust私人结构字段,默认和破坏性?

发布于 2025-02-04 13:38:42 字数 483 浏览 1 评论 0原文

假设我创建了一个结构。

mod foostruct {
    #[derive(Default)]
    pub struct Foo {
        a: u64,
        pub b: u64,
    }
}

该结构是真的,因为可见性规则不能用默认值在外部创建,

Foo { b: 42, ..Default::default() }

并且也不能破坏其可见成员?

let Foo { b, ... } = foo;

我只是和一个朋友进行了交谈,这两个都被抚养长大,而我从未想过。我以前是使用建筑商总是总是,并且没有将破坏/默认设置视为对模式的损害。

Let's say I create a struct.

mod foostruct {
    #[derive(Default)]
    pub struct Foo {
        a: u64,
        pub b: u64,
    }
}

Is it true that this struct, because of the visibility rules can not be created externally with a default,

Foo { b: 42, ..Default::default() }

And, also cannot have it's visible members destructed?

let Foo { b, ... } = foo;

I was just having a conversation with a friend and both of these were brought up, and I just never thought of this. I was previously always using builders, and hadn't considered destruction/defaults as a detriment to the pattern.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

心凉怎暖 2025-02-11 13:38:42

这两个代码都是其他东西的糖,因此我们可以通过检查它们的脱加人来考虑它们的特征。

  foo {b:42,.. default :: default()}
 

粗略的是:

{
    let temp: Foo = Default::default();
    Foo { b: 42, a: temp.a }
}

这是不允许的,因为foo :: a看不到。

 令foo {b,..} = foo;
 

对此的desugars(foo确实是foo)的其他静态类型检查):

let b = foo.b;

允许此,因为私有字段从来都不是读。

Both of these bits of code are sugar for something else, so we can reason about their characteristics by examining what they desugar to.

Foo { b: 42, ..Default::default() }

Desugars to roughly:

{
    let temp: Foo = Default::default();
    Foo { b: 42, a: temp.a }
}

This is disallowed, because Foo::a is not visible.

let Foo { b, .. } = foo;

Desugars to this (with an additional static type-check that foo is indeed a Foo):

let b = foo.b;

This is allowed because the private fields are never actually read.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文