# Slices and Maps — Go (Golang)

Source: https://www.skillbyai.com/en/go/b-slices

> Dynamic arrays and hash maps.

## Shared backing arrays and random map order

A **slice** is a view (pointer, length, capacity) onto an underlying array. Slicing (`a[1:3]`) shares that array, so writes through one slice are visible through the other; use `slices.Clone` or `copy` for an independent copy. `append` may reallocate, so always use its return value. A **map** is a hash table; reading a missing key returns the zero value, and the two-value form (`v, ok := m[k]`) tells you whether it was present. Map iteration order is deliberately random, so sort keys when order matters.

## Aliasing, cloning, append and maps, run

I ran this with Go 1.27.1 (`go run .` in a module named demo, standard library only). Writing through b changes a because they share an array; editing a clone does not. A missing map key returns 0 and false, and sorted keys give a stable order.

```go
package main

import (
	"fmt"
	"slices"
	"maps"
)

func main() {
	a := []int{1, 2, 3, 4}
	b := a[1:3]           // shares a's backing array
	b[0] = 99
	fmt.Println("a:", a, "b:", b, "len(b):", len(b), "cap(b):", cap(b))

	c := slices.Clone(a)  // independent copy
	c[0] = -1
	fmt.Println("a after editing clone:", a)

	var s []int
	for i := range 5 {
		s = append(s, i)  // append may reallocate; always use its return value
	}
	fmt.Println("s:", s)

	stock := map[string]int{"pen": 12, "ink": 0}
	qty, ok := stock["paper"]
	fmt.Println("paper:", qty, ok)
	keys := slices.Sorted(maps.Keys(stock)) // map order is random; sort for stable output
	fmt.Println("keys:", keys)
}
```

Output:

```
a: [1 99 3 4] b: [99 3] len(b): 2 cap(b): 3
a after editing clone: [1 99 3 4]
s: [0 1 2 3 4]
paper: 0 false
keys: [ink pen]
```

## Clone before modifying shared data

If a function receives a slice and must change it without affecting the caller, copy it first.

**Quiz:** What does v, ok := m["key"] tell you when ok is false?

- [x] The key is not in the map, and v is the zero value
- [ ] The map is nil and will panic
- [ ] The value is false
- [ ] The map is sorted

*Answer:* The key is not in the map, and v is the zero value. Comma-ok distinguishes missing from zero.
