calloc equivalent

114 views
Skip to first unread message

RJ

unread,
Nov 11, 2009, 11:42:21 AM11/11/09
to golang-nuts
Hi all,

SImple question. How do I allocate an array of an runtime-determined
size? I didn't see anything obvious in the tutorial or language
specification.

I tried

var d *[...]int= new([flag.NArg()]int);

but I get

map_fun.go:13: invalid array bound flag.NArg()

among other errors, presumably because the type needs a constant in
the array bound. What is the go-ish way to do this?

rj

Russ Cox

unread,
Nov 11, 2009, 12:44:30 PM11/11/09
to RJ, golang-nuts

You can't allocate a variable-sized array, but you can allocate a slice.

var d []int = make([]int, flag.NArg());

or more idiomatically

d := make([]int, flag.NArg());

See also http://golang.org/doc/effective_go.html#slices

Enjoy!
Russ

RJ

unread,
Nov 11, 2009, 2:01:47 PM11/11/09
to golang-nuts
Thanks!

rj
Reply all
Reply to author
Forward
0 new messages