具有未导出字段的Golang结构文字语法 [英] Golang struct literal syntax with unexported fields

查看:108
本文介绍了具有未导出字段的Golang结构文字语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个比较大的结构,直到现在我仍在使用结构文字语法实例化,例如:

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

Thing{
  "the name",
  ...
}

我刚刚在 Thing 结构中添加了一个未导出的字段,现在Go抱怨:在Thing文字中未导出字段'config'的隐式赋值.

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?

推荐答案

您只能使用复合文字如果您在文字中使用键值,则可以创建在另一个包中定义的结构类型的值,因为这样就不需要为所有字段提供初始值,因此可以省去未导出的字段(只有声明包才能设置/更改).

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
}

如果您需要未导出字段具有其类型的零值以外的值的struct值,则包本身必须导出某种构造函数或初始化程序(或setter方法),因为是从外部(包的)),则无法更改/设置未导出的字段.

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.

请参阅相关问题:如何克隆结构字段未导出?

这篇关于具有未导出字段的Golang结构文字语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆