Evan Carroll
Evan Carroll

Reputation: 1

Rust private struct fields and defaults and destructuring?

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.

Upvotes: 0

Views: 1117

Answers (1)

cdhowie
cdhowie

Reputation: 169143

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.

Upvotes: 2

Related Questions