Tuesday, December 22, 2020

The new function in Go

Know everything about the new function in Go, especially when and how to use it.

Apart from the standard way to declare variables, Go offers another way to declare variables via the built-in function new function. Its format is:

myVar := new(myType)

Can you guess what's the type for myVar on the example above? If you guessed *myType, you got it right: the new function returns a pointer to the specified type. So let's understand a little more about it.

A deeper look

Because new always returns a pointer to the specified type, it's fair to say that as with pointers, every call to the new  function will create an unnamed variable, initialize it its zero value and return its address, a pointer to the specified type. For example:

package main

import (
"fmt"
)

func main() {
p := new(int)
fmt.Printf("p: %v, *p: %v, &p: %v", p, *p, &p)
}


p: 0xc000100010, *p: 0, &p: 0xc000102018

When to use the new function?

And when should we use new?

The main reason to use new is that you don't need to declare a new variable just to assign values to your pointers, with the tradeoff that your code becomes less readable.

Think of it as a convenience to abbreviate the three-step process of declaring and assigning values to pointers:

// this block
i := 22
var p *int
p = &i

// could be replaced by this
p := new(int)
*p = 22

Conclusion

On this article we learned about the new function in Go. One of the advantages of using new is that you don't need to declare a dummy variable to assign your pointers to it. But since new returns a pointer to the specified type, it may be confusing for new users of the language. For that reason, the new function is not very used but definitely, it's worth knowing.

See Also

Any comment about this page? Please contact us on Twitter

Featured Article

Pointers in Go

Understand all about declaring and using pointers in Go If you're coming from Python, Java, JavaScript, C# and others, tal...

Popular Posts