Use of nil at initialize slice in struct

437 views
Skip to first unread message

Archos

unread,
Dec 18, 2011, 5:37:14 PM12/18/11
to golang-nuts
I'm initializing slices (defined in structs) to nil since it's shorter
to both to know if they're empty and to initialize them. (newFoo2)

Is it all right os is better to use the another way?

// ===
type foo struct {
deb []string
warn []string
}

func newFoo() *foo {
return &foo{
make([]string, 0),
make([]string, 0),
}
}

func newFoo2() *foo {
return &foo{nil, nil}
}

func main() {
f1 := newFoo()
if len(f1.warn) != 0 {...}

f2 := newFoo2()
if f2.warn != nil {...}
}
// ===

Dave Cheney

unread,
Dec 18, 2011, 5:42:17 PM12/18/11
to Archos, golang-nuts
The zero value for a slice is nil, which has a len of zero. You can just return &foo{} or new(foo) depending on your preference.

Cheers

Dave

Sent from my iPhone

Archos

unread,
Dec 18, 2011, 5:47:27 PM12/18/11
to golang-nuts
That struct was an example. It has more fields in my code but I see
the point. Thanks

On Dec 18, 10:42 pm, Dave Cheney <d...@cheney.net> wrote:
> The zero value for a slice is nil, which has a len of zero. You can just return &foo{} or new(foo) depending on your preference.
>
> Cheers
>
> Dave
>
> Sent from my iPhone
>

Reply all
Reply to author
Forward
0 new messages