Home >Backend Development >Golang >How to Assign True to a Bool Pointer in Go Struct Literals?
In Go, assigning values to pointers within struct literals can be tricky. Specifically, setting a bool pointer to true can require a workaround.
Consider the following function that accepts a bool pointer:
import "fmt" func main() { fmt.Println("Hello, playground") check(handler{is: new(bool)}) } type handler struct{ is *bool } func check(is handler){}
To assign the is field to true in the struct literal, one might assume a simple notation exists:
handler{is: &true} // This is invalid
Unfortunately, this is not valid Go syntax. To set the bool pointer to true, a workaround is required.
One method is to create a slice containing a single bool value of true and index its first element:
h := handler{is: &[]bool{true}[0]} fmt.Println(*h.is) // Prints true
While this allows you to set the pointer to true, it unnecessarily creates a slice array that will remain in memory until the address to its first element is deleted.
A cleaner solution is to create a helper function that returns a pointer to a bool variable initialized to true:
func newTrue() *bool { b := true return &b }
This function can then be used in the struct literal:
h := handler{is: newTrue()} fmt.Println(*h.is) // Prints true
Other options to set the pointer to true include anonymous functions:
h := handler{is: func() *bool { b := true; return &b }()} fmt.Println(*h.is) // Prints true
Or variant:
h := handler{is: func(b bool) *bool { return &b }(true)}
These allow for concise syntax but can be less readable than the helper function approach.
While setting a bool pointer to true in struct literals may seem like a simple task, it requires a specific syntax or the use of a workaround. Knowing these methods empowers Go programmers to effectively assign values to pointers in various situations.
The above is the detailed content of How to Assign True to a Bool Pointer in Go Struct Literals?. For more information, please follow other related articles on the PHP Chinese website!