Map là kiểu dữ liệu key-value tích hợp sẵn trong Go, khai báo bằng m := map[string]int{"a": 1} hoặc make(map[string]int).
- Check key tồn tại:
val, ok := m["key"]—oklà false nếu key không tồn tại (zero value của value type). - Xoá:
delete(m, "key")— không panic nếu key không tồn tại. - Không thread-safe: truy cập concurrent phải dùng
sync.Maphoặc bọc bằng mutex. - Zero value là nil: map nil chỉ đọc được, ghi sẽ panic — phải
makehoặc dùng literal trước khi gán. - Iteration order không xác định: mỗi lần range cho thứ tự khác nhau, là design có chủ ý của Go.
A map is Go's built-in key-value type, declared with m := map[string]int{"a": 1} or make(map[string]int).
- Existence check:
val, ok := m["key"]—okis false when the key is missing (andvalis the value type's zero value). - Delete:
delete(m, "key")— safe to call even if the key is absent. - Not thread-safe: concurrent access requires
sync.Mapor a mutex. - Zero value is nil: a nil map is read-only — writing to it panics. Initialize with
makeor a literal first. - Iteration order is randomized: every range produces a different order — by design.