I have a Node
struct type like this:
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"
}
I have two fields of Node
which are optional and only needed depending upon category
field:
leafPenetration float32 // Needed only if category is "Leaf"
rootPadDim float32 // Needed only if category is "Root"
Is the current Node
implementation fine? What is the best practice for such optional/conditional fields inside struct types?
By default, fields initialize to type's zero value -- in case of float32
it's 0
. To avoid that, it's common to use pointers, for fields that are optional, like:
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"
}
Pointer fields will be defaulted to nil
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With