Dec 31, 2009

Shorthand initialization of structs in Go

They say there is always more than one way to do something, and certainly this is true of Go just as it is of every other programming language.

With regards to initializing structs in Go you may run across an example of initializing something like this where new() is called on the struct type and then each field of the struct has its values filled in one at a time and then finally the struct itself is returned:


package main
import ( "fmt")


type foo struct {
     list   []int
     num    int
     data   string
}

//Here is the initializer
func newFoo(m []int, n int, o string) *foo {
     f := new(foo)
     f.list   = m
     f.num    = n
     f.data   = o
     return f
}

func main(){
     myfoo := newFoo([]int{1,2,3}, 9, "Hello")
     fmt.Printf("%v\n", myfoo)
}

output> &{[1,2,3] 9 Hello}


There is nothing wrong with this style at all, however I've recently discovered a simpler way to initialize structures, newFoo() could have been written like this:



func newFoo(m []int, n int, o string) *foo {
     return &foo{m,n,o}
}


Notice the function is now expecting to return a pointer of type foo (*foo), and the return statment itself preceeds foo with an ampersand (&foo) which means this will return the address of foo instead of foo itself.

I found this to be a useful little tid-bit, I hope you enjoy it.

0 replies: