How to set bool pointer to true in struct literal?

前端 未结 3 534

I have the function below which accepts a bool pointer. I\'m wondering if there is any notation which allows me to set the value of the is field to true

3条回答
  •  长情又很酷
    2021-02-06 23:44

    You can do that but it's not optimal:

    h := handler{is: &[]bool{true}[0]}
    fmt.Println(*h.is) // Prints true
    

    Basically it creates a slice with one bool of value true, indexes its first element and takes its address. No new variable is created, but there is a lot of boilerplate (and backing array will remain in memory until the address to its first element exists).

    A better solution would be to write a helper function:

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

    And using it:

    h := handler{is: newTrue()}
    fmt.Println(*h.is) // Prints true
    

    You can also do it with a one-liner anonymous function:

    h := handler{is: func() *bool { b := true; return &b }()}
    fmt.Println(*h.is) // Prints true
    

    Or a variant:

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

    To see all your options, check out my other answer: How do I do a literal *int64 in Go?

提交回复
热议问题