The new function
- Go course
- Beginner
- Lesson 65/90
- 4 min
Learn to allocate memory returning a pointer with new.
The new function
new(T) allocates a new zero-valued value of type T and returns its address (*T):
p := new(int) // *int, *p == 0
*p = 42
fmt.Println(*p) // 42For structs, the &Type{...} form is usually preferred because the fields can be filled on the same line: u := &Urun{Ad: "Kalem"}.
Constructor functions
Go has no class constructors; instead, functions starting with New that return a pointer are written:
type Sayac struct{ n int }
func NewSayac(baslangic int) *Sayac {
return &Sayac{n: baslangic}
}
s := NewSayac(10)
s.n++
fmt.Println(s.n) // 11A constructor guarantees valid starting values in one place.
Practice Write a constructor
Write type Sayac struct{ n int } and the constructor NewSayac(baslangic int) *Sayac. Create one with s := NewSayac(10), do s.n += 5 and print s.n.
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
type Sayac struct{ n int }
func NewSayac(baslangic int) *Sayac {
return &Sayac{n: baslangic}
}
func main() {
s := NewSayac(10)
s.n += 5
fmt.Println(s.n)
}Expected output
15
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Is it safe in Go for a function to return the address of its local variable?
- No, it becomes invalid memory
- Only with new
- It doesn't compile
- Yes; the compiler moves the value to the heap Correct answer
Explanation: Escape analysis sees the address leave the function and allocates the variable on the heap; no dangling pointer occurs as in C.
2 Allocate a new value
p := ____(float64)
*p = 3.5
p := new(float64)
*p = 3.5
Explanation: new(T) allocates a zero-valued T and returns its address.
3 Expression and type
| Term | Meaning |
|---|---|
new(int) |
*int (value 0) |
&Urun{} |
*Urun |
make([]int, 3) |
[]int (not a pointer) |
NewSayac(10) |
*Sayac |