Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set bool pointer to true in struct literal?

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 in the struct literal; basically without to define a new identifier (i.e. var x := true ; handler{is: &x} )

package main

import "fmt"

func main() {
    fmt.Println("Hello, playground")
    check(handler{is: new(bool) })
}


type handler struct{
    is *bool
}

func check(is handler){}
like image 300
The user with no hat Avatar asked Mar 02 '15 19:03

The user with no hat


3 Answers

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?

like image 175
icza Avatar answered Nov 03 '22 04:11

icza


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.

like image 31
JimB Avatar answered Nov 03 '22 03:11

JimB


This simplest way is to write a short function to turn a bool into a *bool.

func BoolPointer(b bool) *bool {
    return &b
}

h := handler{is: BoolPointer(true)}
like image 6
guissou Avatar answered Nov 03 '22 03:11

guissou