具有未导出字段的Golang结构文字语法

编程入门 行业动态 更新时间:2024-10-23 15:33:22
本文介绍了具有未导出字段的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结构文字语法

本文发布于:2023-07-30 00:38:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1245007.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   语法   结构   文字   Golang

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!