Reputation: 12575
I'm implementing a tree in Go. My TreeNode struct looks like this:
type TreeNode struct {
payload byte
parent *TreeNode
children map[byte]*TreeNode
}
In my implementation, the root node of the tree is a special node that has no payload. Otherwise the payload is always a single lower-case letter from the English alphabet. So my tree initialization function looks like this:
func createEmptyTree(fileName string) *TreeNode{
return &TreeNode{
nil, // Line #180
nil,
false,
map[byte]*TreeNode{},
}
}
When I compile it though, I get the following error: ./main.go:180:9: cannot use nil as type byte in field value
So it seems I cannot use nil
for a byte variable. Is there something else I could use in this situation? I could easily use '0'
or other non alphabetic character. But it seems hacky. What should I do?
Upvotes: 2
Views: 9819
Reputation: 166569
For idiomatic Go, write your function as:
package main
import (
"fmt"
)
type TreeNode struct {
payload byte
parent *TreeNode
children map[byte]*TreeNode
}
func createEmptyTree(fileName string) *TreeNode {
return &TreeNode{
children: map[byte]*TreeNode{},
}
}
func main() {
tree := createEmptyTree("fiename")
fmt.Println(tree)
}
Playground: https://play.golang.org/p/v6DJCnpN6Ys
Output:
&{0 <nil> map[]}
The payload
value for an empty tree is integer zero (0
), the zero-value for the integer type byte
. Zero is not a single lower-case letter value from the English alphabet.
The Go Programming Language Specification
When storage is allocated for a variable, either through a declaration or a call of new, or when a new value is created, either through a composite literal or a call of make, and no explicit initialization is provided, the variable or value is given a default value. Each element of such a variable or value is set to the zero value for its type: false for booleans, 0 for numeric types, "" for strings, and nil for pointers, functions, interfaces, slices, channels, and maps.
Upvotes: 4
Reputation: 1324218
byte
is a numeric type, actually an alias for uint8
.
That means it has default zero value of 0.
Upvotes: 16
Reputation: 6994
Every type in golang has a zero value. In the case of byte
that is the null byte.
It's entirely possible to just use the null byte as a magical zero payload at the root.
Upvotes: 0