Rust私人结构字段,默认和破坏性?
假设我创建了一个结构。
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这两个代码都是其他东西的糖,因此我们可以通过检查它们的脱加人来考虑它们的特征。
粗略的是:
这是不允许的,因为
foo :: a
看不到。对此的desugars(
foo
确实是foo
)的其他静态类型检查):允许此是,因为私有字段从来都不是读。
Both of these bits of code are sugar for something else, so we can reason about their characteristics by examining what they desugar to.
Desugars to roughly:
This is disallowed, because
Foo::a
is not visible.Desugars to this (with an additional static type-check that
foo
is indeed aFoo
):This is allowed because the private fields are never actually read.