Go
Beginner
1 min read
Pointers, Slices, and Maps
Example
package main
import "fmt"
func increment(n *int) {
*n++
}
func main() {
// Pointers
x := 10
p := &x
fmt.Println("x =", x, " *p =", *p)
increment(&x)
fmt.Println("after increment, x =", x)
// Arrays vs slices
arr := [3]int{1, 2, 3} // fixed-size array
sl := arr[:] // slice of the array
sl = append(sl, 4, 5) // grows beyond original array
fmt.Println("arr:", arr) // unchanged
fmt.Println("sl :", sl)
// make a slice directly
nums := make([]int, 0, 5)
for i := 0; i < 5; i++ {
nums = append(nums, i*i)
}
fmt.Println("squares:", nums)
// Maps
scores := map[string]int{
"Alice": 95,
"Bob": 87,
}
scores["Carol"] = 91
if v, ok := scores["Dave"]; ok {
fmt.Println("Dave:", v)
} else {
fmt.Println("Dave not found, zero value:", v)
}
for name, score := range scores {
fmt.Printf("%s: %d\n", name, score)
}
}