Summary - Pointer
- Go course
- Beginner
- Lesson 68/90
- 4 min
Write a counter increment function with & and *.
Pointers summary
&x takes an address, *p reads/writes the value at the address, *T is a pointer type and its zero value is nil. Pointers are for changing values and for sharing large values without copying; they are created with new(T) or &T{...}; don't forget nil checks. Go has no pointer arithmetic, and returning the address of a local variable is safe.
A linked list example
A classic use of pointers is nodes linked to each other:
type Dugum struct {
Deger int
Sonraki *Dugum
}
bas := &Dugum{1, &Dugum{2, &Dugum{3, nil}}}
for d := bas; d != nil; d = d.Sonraki {
fmt.Print(d.Deger, " ")
}
// 1 2 3The last node's Sonraki field is nil; the loop ends when it reaches nil.
Practice Linked list sum
Write the Dugum type above. Build the list 1 → 2 → 3 → 4 and compute and print the sum of its values with a loop.
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
type Dugum struct {
Deger int
Sonraki *Dugum
}
func main() {
bas := &Dugum{1, &Dugum{2, &Dugum{3, &Dugum{4, nil}}}}
toplam := 0
for d := bas; d != nil; d = d.Sonraki {
toplam += d.Deger
}
fmt.Println(toplam)
}Expected output
10
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 If you pass a slice to a function and set <code>s[0] = 9</code> inside, does the caller's slice change?
- Yes; the slice shares the underlying array, no pointer needed Correct answer
- No, a copy is taken
- Only with *[]int
- It doesn't compile
Explanation: The slice header is copied but points to the same array, so element changes are visible. Length changes via append, however, aren't.
2 Next node
for d := bas; d != nil; d = d.____ {
toplam += d.Deger
}
for d := bas; d != nil; d = d.Sonraki {
toplam += d.Deger
}
Explanation: d = d.Sonraki moves to the next node.
3 Group summary
| Term | Meaning |
|---|---|
&x |
Address |
*p |
Value |
new(T) |
Zero-valued allocation |
nil |
No value |