我有一个Node这样的结构类型:
package tree
// Enum for node category
type Level int32
const (
Leaf Level = iota + 1
Branch
Root
)
type Node struct {
Children []*Node
Parent *Node
X float32
Y float32
Z float32
Dim float32
Category Level
LeafPenetration float32 // Needed only if category is "Leaf"
RootPadDim float32 // Needed only if category is "Root"
}
Run Code Online (Sandbox Code Playgroud)
我有两个字段Node是可选的,仅根据category字段需要:
leafPenetration float32 // Needed only if category is "Leaf"
rootPadDim float32 // Needed only if category is "Root"
Run Code Online (Sandbox Code Playgroud)
目前的Node实施情况好吗?结构类型内的此类可选/条件字段的最佳实践是什么?
默认情况下,字段初始化为类型的零值——如果float32是0. 为了避免这种情况,通常对可选字段使用指针,例如:
type Node struct {
Children []*Node
Parent *Node
X float32
Y float32
Z float32
Dim float32
Category Level
// Optional fields
LeafPenetration *float32 // Needed only if category is "Leaf"
RootPadDim *float32 // Needed only if category is "Root"
}
Run Code Online (Sandbox Code Playgroud)
指针字段将默认为nil。