How to set bool pointer to true in struct literal?

前端 未结 3 541

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条回答
  •  旧时难觅i
    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
    

提交回复
热议问题