Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang struct literal syntax with unexported fields

I've got a largish struct which until just now I was instantiating with the struct literal syntax, e.g.:

Thing{
  "the name",
  ...
}

I've just added an unexported field the Thing struct and now Go is complaining: implicit assignment of unexported field 'config' in Thing literal.

Is there any way I can continue using the literal syntax even though there's now an unexported field on the struct?

like image 498
jbrown Avatar asked Jul 20 '17 11:07

jbrown


People also ask

How to give values in struct in golang?

Default values can be assigned to a struct by using a constructor function. Rather than creating a structure directly, we can use a constructor to assign custom default values to all or some of its members.

What is an exported field in Golang?

In go, fields and variables that start with an Uppercase letter are "Exported", and are visible to other packages. Fields that start with a lowercase letter are "unexported", and are only visible inside their own package.

How to declare a struct variable in golang?

The declaration starts with the keyword type, then a name for the new struct, and finally the keyword struct. Within the curly brackets, a series of data fields are specified with a name and a type.

How to write struct in golang?

Defining a struct typeThe type keyword introduces a new type. It is followed by the name of the type ( Person ) and the keyword struct to indicate that we're defining a struct . The struct contains a list of fields inside the curly braces. Each field has a name and a type.


1 Answers

You can only use composite literals to create values of struct types defined in another package if you use keyed values in the literal, because then you are not required to provide initial values for all fields, and so you can leave out unexported fields (which only the declaring package can set / change).

If the type is declared in the same package, you can set unexported fields too:

t := Thing{
    Name:           "the name",
    someUnexported: 23,
}

But you can only provide initial values for exported fields if the type is declared in another package, which is not a surprise I guess:

t := otherpackage.Thing{
    Name: "the name",
    // someUnexported will implicitly be its zero value
}

If you need values of the struct where the unexported fields have values other than the zero value of their types, the package itself must export some kind of constructor or initializer (or setter method), because from the outside (of the package), you can't change / set unexported fields.

See related question: How to clone a structure with unexported field?

like image 141
icza Avatar answered Sep 20 '22 11:09

icza