Home > Back-end >  check whether the embedded struct inside a struct is nil?
check whether the embedded struct inside a struct is nil?

Time:09-20

Let's say I have two structs. Point and ColoredPoint. Point is embedded into ColoredPoint.

type Point struct {
    X, Y int
}

type ColoredPoint struct {
    R, G, B int
    Point
}

func Check(p *ColoredPoint) {
    if p.Point != nil { // won't work here.
        // do something
    }
}

I want to check whether the embedded struct in ColoredPoint, i.e., Point exists before doing something, however, p.Point != nil isn't a valid statement.

Is there a way to check whether the embedded struct inside a struct is nil?

CodePudding user response:

The Point embedded type in your ColoredPoint is not a pointer type. Therefore it can't be checked for nil, but can be checked against a zero value literal of that type using Point{} to check if the members are not modified

func Check(p *ColoredPoint) {
    if (Point{}) == p.Point {
        fmt.Println("p.Point is nil")
    }
}

To guard against nil value of p, you could combine that check with p != nil && ..

  •  Tags:  
  • go
  • Related