DEV Community

Nick Huanca
Nick Huanca

Posted on

1

More easily leveraging bool's from a ptr

I am currently working on a project that leverages pointers to Bool values in golang. I am using corev1.SecurityContext.RunAsNonRoot which is a *bool. When I am doing comparisons, I have to wrap all the checks for true/false in a helper function since I cannot be sure if the value will be unset (nil) which will cause a fatal error.

Is there some other golang trick or pro-tip I should be using? Or is there some other type of method I should consider when using libraries that have this type of struct referencing *bool?

Any discussion would be so great! Happy Thursday!

Top comments (2)

Collapse
 
maxatome profile image
Maxime Soulé

You can use this code:

isItTrue := boolPtr != nil && *boolPtr

or use a helper function, as it will probably be inlined by the compiler.
Note that your isNilbool function is useless. Using a function to do a simple == is overkill.

Collapse
 
nickhuanca profile image
Nick Huanca

thanks for the helpful feedback Maxime - I'll definitely adjust my approach :)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay