9
type MyStruct struct {

    IsEnabled *bool
}

How do I change value of *IsEnabled = true

None of these work:

*(MyStruct.IsEnabled) = true
*MyStruct.IsEnabled = true
MyStruct.*IsEnabled = true
vastlysuperiorman
  • 1,694
  • 19
  • 27
Taranfx
  • 10,361
  • 17
  • 77
  • 95

1 Answers1

16

You can do this by storing true in a memory location and then accessing it as seen here:

type MyStruct struct {
    IsEnabled *bool
}


func main() {
    fmt.Println("Hello, playground")
    t := true // Save "true" in memory
    m := MyStruct{&t} // Reference the location of "true"
    fmt.Println(*m.IsEnabled) // Prints: true
}

From the docs:

Named instances of the boolean, numeric, and string types are predeclared. Composite types—array, struct, pointer, function, interface, slice, map, and channel types—may be constructed using type literals.

Since boolean values are predeclared, you can't create them via a composite literal (they're not composite types). The type bool has two const values true and false. This rules out the creation of a literal boolean in this manner: b := &bool{true} or similar.

It should be noted that setting a *bool to false is quite a bit easier as new() will initialize a bool to that value. Thus:

m.IsEnabled = new(bool)
fmt.Println(*m.IsEnabled) // False
vastlysuperiorman
  • 1,694
  • 19
  • 27