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
Release: 2024-12-15 07:20:11
Original
120 people have browsed it

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]}
Copy after login

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template