tags:

views:

130

answers:

1

It seems pointless to be used in primitive language constructs, as you can't specify any sort of values

func main() {
    y := new([]float)
    fmt.Printf("Len = %d", len(*y) ) // => Len = 0
}

For stucts it makes a bit more sense, but what's the difference between saying y := new(my_stuct) and the seemingly more concise y := &my_struct?

And since anything you create is based on those primitives, they will be initialized to the said zero values. So what's the point? When would you ever want to use new()?

Sorry for the very-beginner question, but the documentation isn't always that clear.

+4  A: 

You can't use new for slices and maps, as in your code example, but instead you must use the make command: make([]float, 100)

Both new(MyStruct) and &MyStruct{} do to the same thing, because Go will allocate values on the heap if you get their address with &. Sometimes the code just expresses it intent better in one style or the other.

Go does not have built-in support for constructors, so usually you would wrap the call to new into a function, for example NewMyStruct() which does all the necessary initialization. It also makes it possible to initialize private fields or hide the struct behind an interface, to prevent users of the object from directly messing with its internals. Also evolving the structure of the struct is easier that way, when you don't need to change all of its users when adding/removing/renaming/reordering fields.

Esko Luontola
Regarding using new, I guess that's a compiler error that makes that code valid, compilable code? Or is something else going on?
aharon
I suppose calling new on slices allocates something, but it's not a usable slice. Slices and maps require some special initialization, and the make call does that. (I think that it's a deficiency in the language design that make is needed for some built-in types, but that's just the way it's now. Maybe if generics or constructors are added at some point, make would not be needed.)
Esko Luontola
I see. So I guess the answer is, you don't.
aharon
newacct