You often golang convert slice into map to get O(1) lookups: treat slice entries as set keys, index structs by an ID, or group duplicates into map[K][]V. Maps need comparable keys; slices and maps cannot be keys themselves. For map basics, see maps in Go.
Tested with Go 1.24 on Linux.
Elements as keys (set-like)
package main
import "fmt"
func main() {
numbers := []int{1, 2, 3, 4}
m := make(map[int]bool)
for _, n := range numbers {
m[n] = true
}
fmt.Println(len(m), m[3])
}You should see 4 and true.
Slice of structs keyed by a field
package main
import "fmt"
type Item struct {
ID int
Name string
}
func main() {
items := []Item{{1, "a"}, {2, "b"}}
byID := make(map[int]Item)
for _, it := range items {
byID[it.ID] = it
}
fmt.Println(byID[2].Name)
}You should see b.
Index as key
package main
import "fmt"
func main() {
numbers := []int{10, 20, 30}
m := make(map[int]int)
for i, v := range numbers {
m[i] = v
}
fmt.Println(m[1])
}You should see 20.
Duplicates: map key to slice of indices
package main
import "fmt"
func main() {
numbers := []int{1, 2, 2, 3}
m := make(map[int][]int)
for i, n := range numbers {
m[n] = append(m[n], i)
}
fmt.Println(m[2])
}You should see [1 2] (indices where value 2 appears).
Summary
Converting a slice to a map is a for range over the slice plus clear rules for keys, values, and overwrite behavior. Use map[K]bool or struct{} for sets, map[K]T keyed by IDs for structs, and map[K][]int (or similar) when duplicates must be preserved.

