英文:
What does a const value do in an anonymous struct field?
问题
在ListNode
结构体中将NodeType
类型作为匿名字段的目的是什么?它是否作为结构体的某种标识符?
英文:
Given the following code:
type NodeType int
const (
NodeText NodeType = iota
NodeAction
// etc..
)
type ListNode struct {
NodeType
}
What is the explanation of including the NodeType
type as an anonymous field in the ListNode
struct? Does it serve as some sort of identifier for the struct?
答案1
得分: 2
根据《Go编程语言规范》,对于这样的“匿名”或“嵌入字段”,
未限定的类型名称充当字段名。
在你的情况下,你可以这样写:
var node1 ListNode
node1.NodeType = NodeText
或者
node2 := ListNode{NodeText}
或者
node3 := ListNode{
NodeType: NodeText,
}
这三种方式创建的值是相同的。
英文:
For such an anonymous or embedded field, per The Go Programming Language Specification,
> The unqualified type name acts as the field name.
In your case, you can write the following:
var node1 ListNode
node1.NodeType = NodeText
or
node2 := ListNode{NodeText}
or
node3 := ListNode{
NodeType: NodeText,
}
All three create the same value.
答案2
得分: 2
NodeType
不是一个常量,它是一个类型,并且已经嵌入到ListNode
结构体中。
例如,你可以按照以下方式设置ListNode
的NodeType
:
ln := &ListNode{NodeType: NodeText}
fmt.Println(ln)
// 输出:&{0}
更多阅读:http://www.goinggo.net/2014/05/methods-interfaces-and-embedded-types.html(向下滚动)和 https://golang.org/doc/effective_go.html#embedding
英文:
NodeType
isn't a constant. It's a type, and it has been embedded into the ListNode
struct.
> Struct types have the ability to contain anonymous or embedded fields.
> This is also called embedding a type. When we embed a type into a
> struct, the name of the type acts as the field name for what is then
> an embedded field.
e.g. You would set the NodeType
for a ListNode
as per below:
ln := &ListNode{NodeType: NodeText}
fmt.Println(ln)
// Outputs: &{0}
Further reading: http://www.goinggo.net/2014/05/methods-interfaces-and-embedded-types.html (scroll down) and https://golang.org/doc/effective_go.html#embedding
答案3
得分: 2
这不是一个“匿名字段”,所使用的语言特性称为“嵌入”,这是Go语言处理继承的方式。在Go中,如果StructA
嵌入了StructB
,那么StructB
上的字段和以StructB
为接收者类型的方法将直接在StructA
上可访问。但是,导出和未导出的规则仍然适用(即在StructB
中未导出的字段将像普通字段一样无法在包的范围之外访问)。我无法说出你为什么想要在所有结构体中都有这个值,这只是一种高效的做法。归根结底,它只是一个整数,通过不给它一个实际的名称,你只是节省了几行代码,没有其他特别之处。
英文:
That is not an 'anonymous field' the language feature being used is called 'embedding' and it's sort of Go's way of addressing inheritance. In Go, if StructA
embeds StructB
then fields on StructB
and methods with a receiving type of StructB
will become directly accessible on StructA
. Same rules for exported vs unexported apply however (ie unexported fields in StructB
won't be accessible outside the packages scope like normal). I can't say why you want this value in all your structs, this is just an efficient way of doing it. At the end of the day it's just an int and you're just saving a few lines of code by not giving it an actual name, nothing more really.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论