Home >Backend Development >Golang >Can a Go Struct Literal Directly Assign a True Boolean Pointer Without Extra Variables?

Can a Go Struct Literal Directly Assign a True Boolean Pointer Without Extra Variables?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-15 07:20:11119browse

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:

  • Helper Function:
func newTrue() *bool {
    b := true
    return &b
}
h := handler{is: newTrue()}
  • Anonymous Function:
h := handler{is: func() *bool { b := true; return &b }()}
  • One-Liner Variant:
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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn