How to set bool pointer to true in struct literal?

前端 未结 3 537

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?

    0 讨论(0)
  • 2021-02-06 23:46

    One of the reasons why pointers are helpful in go or any language for that matter, is they help us to "pass by reference". So if we pass anything by reference we can then "change" that thing. A function which takes a pointer to bool, can change the bool's value effectively even after the function returns. This is the very thing we do not want with constants, ie. their values should not change. Hence this restriction makes sense.

    Apart from the tricks mentioned by icza above, would want to add a point here. Mostly we use pointers to bools rather than bools directly in order to use the nil value of pointers effectively, which otherwise have to be either true or false. If that IS the case, then you might want to use optional bool flags directly in the functions, rather than have pointers to bool or even a struct wrapping the single bool pointer as shown in your example, doing away with the complete requirement of a struct even.. Now, of course if the struct is reqd for any other reason, you can very well use any of the tricks by icza above. Btw, you can directly have a copy of the bool value for using the adress of as below as well.

    const check = true
    chk := check
    fmt.Println(&chk) // will give you the address of chk
    chk = false
    fmt.Println(chk) // will print false
    fmt.Println(check) // will print true
    
    0 讨论(0)
  • 2021-02-06 23:48

    No.

    There is no syntax to define a pointer to a primitive type, other than the zero value returned by new. The same goes for numeric types, and strings.

    You either need to create a value before hand to take the address of, or you create the pointer with a zero value, and assign a new value after the fact.

    0 讨论(0)
提交回复
热议问题