Creating pointer to boolean without new()

12,198 views
Skip to first unread message

Scott Lawrence

unread,
Aug 16, 2010, 12:13:50 AM8/16/10
to golang-nuts
dest := &bool{}

gives me "invalid type for composite literal: bool" - is there any way
to create a pointer to a boolean without using new()?

--
Scott Lawrence

andrey mirtchovski

unread,
Aug 16, 2010, 12:20:01 AM8/16/10
to golang-nuts
would this help?

$ cat t.go
package main
func main() {
var t bool
z:=&t
*z = true
}
$ 6g t.go
$

Rob 'Commander' Pike

unread,
Aug 16, 2010, 12:20:04 AM8/16/10
to Scott Lawrence, golang-nuts

On Aug 16, 2010, at 2:13 PM, Scott Lawrence wrote:

> dest := &bool{}
>
> gives me "invalid type for composite literal: bool" - is there any way
> to create a pointer to a boolean without using new()?

No.

-rob


Rob 'Commander' Pike

unread,
Aug 16, 2010, 12:21:11 AM8/16/10
to andrey mirtchovski, golang-nuts

Yes.

-rob

Steven

unread,
Aug 16, 2010, 1:03:38 AM8/16/10
to Rob 'Commander' Pike, andrey mirtchovski, golang-nuts

Not sure why you're declaring the bool first, it seems unnecessary:
t := true
z := &t

If anything, I would allocate the pointer first, then initialize it in a block:
var z *bool; { t := true; z = &t }
This is essentially equivalent to what you'd expect from:
z := &bool{ true }

But, I'm really not sure why you'd want to avoid:
z := new(bool) // *z is false by default
*z = true

bflm

unread,
Aug 16, 2010, 4:13:34 AM8/16/10
to golang-nuts
On Aug 16, 6:13 am, Scott Lawrence <byt...@gmail.com> wrote:
> dest := &bool{}
>
> gives me "invalid type for composite literal: bool" - is there any way
> to create a pointer to a boolean without using new()?

Just out of curiosity - what's wrong with 'dest := new(bool)'?

Scott Lawrence

unread,
Aug 16, 2010, 9:36:24 AM8/16/10
to bflm, golang-nuts
I had gotten the sense that new() was being deprecated. Obviously not.

--
Scott Lawrence

Jessta

unread,
Aug 16, 2010, 10:04:18 AM8/16/10
to Scott Lawrence, bflm, golang-nuts
On Mon, Aug 16, 2010 at 11:36 PM, Scott Lawrence <byt...@gmail.com> wrote:
> I had gotten the sense that new() was being deprecated. Obviously not.
>

What gave you that impression? new() is there for a reason.
You can't allocate memory for any of the standard types without new()

also new() is far clearer in stating your intention.
dest := &sometype{} // says, get me a pointer to this thing(which will
be on the heap if it escapes or on the heap if it doesn't)

dest := new(sometype) //says, allocate me some space on the heap
because I expect it to escape.

- jessta
--
=====================
http://jessta.id.au

Reply all
Reply to author
Forward
0 new messages