Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional/optional fields in struct type

Tags:

struct

go

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?

like image 984
user3405291 Avatar asked Oct 15 '25 04:10

user3405291


1 Answers

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.

like image 132
Grigoriy Mikhalkin Avatar answered Oct 18 '25 01:10

Grigoriy Mikhalkin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!