Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

check whether the embedded struct inside a struct is nil?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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 && ..

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading