resource:

https://go.dev/blog/maps

constant errors : https://dave.cheney.net/2016/04/07/constant-errors

maps are like dictionaries in python, it has key and value associated with the key

syntax


map[KeyType]ValueType

map type in go is a reference type like slices and pointer, so when we declare a map in the following way var m map[string]int the m variable is pointing to nil, and is not pointing to a memory location of an initialised map if we try to do the lookup it don’t produce any error but when we try to write to it, it produces a fatal error because it can’t write as it don’t have any memory allocated to it proper or suggested way to declare a map:

var m = make(map[string]int)

var m = map[string]string{}

when we modify a map using a method it actually modifies the value, it don’t modify a copy of the map but changes the original map

what are reference types?

reference types hold a reference to the data, not the actual data, so when reference types are passed around through functions or methods a copy of the reference is passed, so any changes make using the reference will change the actual map in the memory location

slices, channels, maps and pointer are reference types in go

package main

import "fmt"

func main() {
    // 's1' and 's2' share the same underlying array data
    s1 := []int{1, 2, 3}
    s2 := s1

    // 'm1' and 'm2' share the same underlying map data
    m1 := map[string]int{"a": 1, "b": 2}
    m2 := m1

    // 'c1' and 'c2' share the same underlying channel
    c1 := make(chan int)
    c2 := c1

    // 'x' is a variable that holds the memory address of an integer
    x := 42
    y := &x // 'y' is a variable that holds the memory address of 'x'

    fmt.Println(s1, s2)       // Output: [1 2 3] [1 2 3]
    fmt.Println(m1, m2)       // Output: map[a:1 b:2] map[a:1 b:2]
    fmt.Println(c1, c2)       // Output: 0xc0000b2000 0xc0000b2000
    fmt.Println(x, *y)        // Output: 42 42
}

CRUD (create, read, update, delete)

creating a new value in map:

mapVar[key] = value