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?
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.
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
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.