New. Along with the var keyword, the new() built-in function in Go can be used to create instances of types. The types are initialized to their default values (which is often 0).
While make can be used to initialize channels, slices and maps, new() can be used on structs, arrays and even values like ints. In most programs, the simplest syntax is best.
Example. The var keyword can be used in the same way as the new built-in. But var returns the object itself, while new() returns a reference to the allocated object.
Part 1 We use the var keyword to initialize some int local variables. With var, the default value 0 is always used to initialize the type.
Part 2 With new(), we get a pointer to the allocated object. We can use a star to get the value of the object.
package main
import "fmt"
type Bird struct {
feathers int;
}
func main() {
// Part 1: use var for local variables that are initialized to default value 0.
var local1 int
var local2 int = 0
fmt.Println("local1", local1)
fmt.Println("local2", local2)
// Part 2: use new for local variable, and then modify it.
local3 := new(int)
*local3 = 30
fmt.Println("local3", *local3)
// Part 3: use new for custom type, and display its value.
bird1 := new(Bird)
fmt.Println("bird1", *bird1)
// Part 4: use var initialization for custom type, and modify it.
var bird2 Bird
bird2.feathers = 200
fmt.Println("bird2", bird2)
}local1 0
local2 0
local3 30
bird1 {0}
bird2 {200}
Summary. In the Go language, new() allocates memory for a variable. Functions like make() can be thought of as ways to call new() along with some other initializations.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jan 25, 2025 (edit link).