Home >Backend Development >Golang >Can a Go Struct Literal Directly Assign a True Boolean Pointer Without Extra Variables?
Setting Boolean Pointer to True in Struct Literals
Question:
A function requires a pointer to a boolean value. Can a struct literal be used to set the field to true without introducing additional variables?
Answer:
Yes, it is possible, but not ideal:
h := handler{is: &[]bool{true}[0]}
This solution creates a slice with a single boolean value of true, indexes its first element, and assigns its address to the is field. While new variables are avoided, the boilerplate and persistence of the backing array present drawbacks.
Better Solutions:
func newTrue() *bool { b := true return &b }
h := handler{is: newTrue()}
h := handler{is: func() *bool { b := true; return &b }()}
h := handler{is: func(b bool) *bool { return &b }(true)}
For more options, refer to "How do I do a literal *int64 in Go?".
The above is the detailed content of Can a Go Struct Literal Directly Assign a True Boolean Pointer Without Extra Variables?. For more information, please follow other related articles on the PHP Chinese website!