Golang struct literal syntax with unexported fields

我只是一个虾纸丫 提交于 2020-01-23 07:08:06

问题


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?


回答1:


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?




回答2:


one more point to add. all properties of a structure should start with capital letter for example:

t := Thing
{

    Name: "the name", // <-- This will work because Name start with capital letter 

    someUnexported: 23, // <-- this wont work because someUnexported starts with small letter
}


来源:https://stackoverflow.com/questions/45213365/golang-struct-literal-syntax-with-unexported-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!