If you are coming from another language, especially one that uses constructors, it may appear that new should be all you need, but Go is not those languages, nor does it have constructors. Would no longer be possible, requiring more special cases in the grammar to permit *new(byte, length). new always returns a *T for the T passed to it.Again more special cases to have to remember, whereas before new took exactly one argument, the type. For slices and channels, new would have to become variadic, taking a possible length, buffer size, or capacity, as required.This is a rule that every Go programmer would have to remember. new would have special behaviour if the type passed to new was a slice, map or channel.Yes, new could be extended to operate like make for slices, maps and channels, but that would introduce its own inconsistencies. s := new(string)įmt.Println(*c = nil) // true Sure, but these are just rules, we can change them, right ?įor the confusion they may cause, make and new are consistent make only makes slices, maps, and channels, new only returns pointers to initialised memory. Using new to construct a pointer to a slice, map, or channel zero value works today and is consistent with the behaviour of new. ![]() New(T) always returns a *T pointing to an initialised T. As Go doesn’t have constructors, the value will be initialised to T‘s zero value. ![]() Why can’t we use new for everything ?Īlthough the use of new is rare, its behaviour is well specified. X1 and x2 have the same type, *int, x2 points to initialised memory and may be safely dereferenced, the same is not true for x1. ![]() If new was removed in favour make, how would you construct a pointer to an initialised value ? var x1 *int Go does not have user defined generic types, but it does have several built in types that can operate as generic lists, maps, sets, and queues slices, maps and channels.īecause make is designed to create these three built in generic types, it must be provided by the runtime as there is no way to express the function signature of make directly in Go.Īlthough make creates generic slice, map, and channel values, they are still just regular values make does not return pointer values. On the surface it appears that make and new do very similar things, so what is the rationale for having both ? Why can’t we use make for everything ? It is fair that commenters point out this redundancy in the language and this sometimes leads them to search for other inconsistencies, most notably the redundancy between make and new. Among them is the ability to take the address of a struct literal which leads to serveral ways to do the same thing. Created by rileyjshaw.This is a post about Go’s built in make and new functions.Īs Rob Pike noted at Gophercon this year, Go has many ways of initialising variables.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |