Preventing the use of a struct key/value constructor


#1

I have a simple struct which I want to make public, but I want to restrict how users can construct it.

So I have something like this:

struct Foo {
  bar: u16
}

I have then defined a constructor using the new convention:

impl Foo {
  fn new(bar: u16) -> Option<Foo> {
    // .. implementation
}

I only want users to use my new constructor, not the default like this:

Foo { bar: 12 }

Is this possible? I’m wondering if it’s as simple as marking bar as private, but intuitively that doesn’t seem correct.


#2

Actually, everything is private by default. You probably want pub struct Foo, and pub fn new, but just don’t write pub bar and you’ll have the semantics you want.


#3

Ah, too easy. Thank you!