-1

With the following code:

var example *bool
example = true
log.Print(example)

I have the following error cannot convert true (untyped bool constant) to *bool

I manage to solve it declaring a new variable truevalue:

var example *bool
truevalue := true
example = &truevalue
log.Print(example)

But I imagine there is a better way to do it, without declaring any new variables.

pcampana
  • 2,413
  • 2
  • 21
  • 39
  • 3
    Well, that pointer has to point _somewhere_. – Sergio Tulentsev Jan 21 '21 at 14:07
  • Unfortunately there is no better way. – cn007b Jan 21 '21 at 14:11
  • 2
    There are several (cumbersome) ways to do this. They're all cataloged [here](https://stackoverflow.com/questions/30716354/how-do-i-do-a-literal-int64-in-go). Your approach is the one I usually take, though. – Jonathan Hall Jan 21 '21 at 14:13
  • @Flimzy the solutions in the example are cumbersome because the need is different, they're trying to assign to a pointer field of a struct literal. – Adrian Jan 21 '21 at 14:14
  • 1
    @Adrian: Which is another way of saying "without declaring new variables", no? – Jonathan Hall Jan 21 '21 at 14:16
  • @Flimzy I don't think so, no. My understanding of the question is that `example` is the only variable they want to declare, and they want to avoid declaring a new variable (`truevalue` in the post), which they can do just using `new()` to initialize the pointer. – Adrian Jan 21 '21 at 14:22
  • 2
    @Adrian: But then you have a zero value. The OP seems to want to set an explicit value. – Jonathan Hall Jan 21 '21 at 14:25
  • @Flimzy you have a pointer to a zero value, which you can then easily set to an explicit value without needing to create an extra variable, thereby solving the stated problem. – Adrian Jan 21 '21 at 15:27
  • 1
    See [Value and Pointer Conversions](https://godoc.org/github.com/aws/aws-sdk-go/aws#hdr-Value_and_Pointer_Conversion_Utilities) in the AWS SDK for one way to handle this problem. More often than not, people asking this question are grappling with the AWS SDK. – Charlie Tumahai Jan 21 '21 at 17:01

1 Answers1

8

A pointer has to point to something, which means you have to either assign it to the address of another variable (as in your second example), or initialize it with new() and then assign by dereference. Personally I'd recommend the former, as new is not widely used in Go. But, for demonstration:

example := new(bool)
*example = true

https://play.golang.org/p/0VO5jNPMutQ

Adrian
  • 42,911
  • 6
  • 107
  • 99