Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference a boolean for assignment in a struct

Tags:

go

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
like image 549
Taranfx Avatar asked Sep 02 '15 22:09

Taranfx


People also ask

How do you call a Boolean function in C#?

Syntax: public bool Equals (bool obj);

How can set boolean value to true in C#?

One of them is ' bool . ' The ' bool ' type can store only two values: true or false . To create a variable of type bool, do the same thing you did with int or string . First write the type name, ' bool ,' then the variable name and then, probably, the initial value of the variable.

Is bool a struct C#?

C# Built-In Structures: The Boolean Type. As seen in previous lessons, the bool data type is used to represent a value considered as being true or false. In the . NET Framework, the bool data type is represented by the Boolean structure.

How do you declare a boolean variable?

Boolean variables are variables that can have only two possible values: true, and false. To declare a Boolean variable, we use the keyword bool. To initialize or assign a true or false value to a Boolean variable, we use the keywords true and false.


1 Answers

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
like image 163
vastlysuperiorman Avatar answered Oct 15 '22 06:10

vastlysuperiorman