Home > Backend Development > Golang > How Can I Efficiently Set a Bool Pointer to True within a Go Struct Literal?

How Can I Efficiently Set a Bool Pointer to True within a Go Struct Literal?

DDD
Release: 2024-12-02 09:21:12
Original
155 people have browsed it

How Can I Efficiently Set a Bool Pointer to True within a Go Struct Literal?

Setting Bool Pointer in a Struct Literal

In Go, when passing a pointer to a bool into a function, it's possible to set the value of the bool field in the struct literal directly. However, the standard syntax requires defining a new identifier, as seen below:

func check(is handler){}

type handler struct{
    is *bool
}

func main() {
    var x bool = true
    check(handler{is: &x})
}
Copy after login

To circumvent this requirement and set the bool pointer to true directly in the struct literal, there are several approaches:

Option 1: Using a Slice

This method creates a slice with a single bool of value true, indexes its first element, and takes its address:

h := handler{is: &[]bool{true}[0]}
Copy after login

While this technique avoids defining a new variable, it introduces unnecessary boilerplate and leaves a backing array in memory.

Option 2: Using a Helper Function

A more optimal solution is to create a helper function that generates a bool pointer with a true value:

func newTrue() *bool {
    b := true
    return &b
}
Copy after login

With this function, setting the bool pointer in the struct literal becomes:

h := handler{is: newTrue()}
Copy after login

Option 3: Using One-Liner Anonymous Functions

Another method involves using anonymous functions to accomplish the same task in a single line:

h := handler{is: func() *bool { b := true; return &b }()}
Copy after login

Option 4: Variant with Anonymous Function

A slight variation of the previous approach:

h := handler{is: func(b bool) *bool { return &b }(true)}
Copy after login

These techniques provide alternatives for setting a bool pointer to true in a struct literal without the need for additional identifiers or unnecessary overhead. Developers can choose the approach that best suits their needs and style preferences.

The above is the detailed content of How Can I Efficiently Set a Bool Pointer to True within a Go Struct Literal?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template