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.
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.
var
keyword to initialize some int
local variables. With var
, the default value 0 is always used to initialize the type.new()
, we get a pointer to the allocated object. We can use a star to get the value of the object.var
instead of new for custom types. We do not need the star operator to get the value, as we do not have a pointer.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}
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.