67 lines
1.7 KiB
Go
67 lines
1.7 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"reflect"
|
|
)
|
|
|
|
type FavoriteNumbers struct {
|
|
num1, num2, num3 int
|
|
}
|
|
|
|
func main() {
|
|
fmt.Println("Map, maps keys to values")
|
|
fmt.Println("Zero value of a map is nil")
|
|
fmt.Println("make function return a map of the given type, initialized and ready for use")
|
|
|
|
m := make(map[string]FavoriteNumbers)
|
|
/* or:
|
|
var m map[string]FavoriteNumbers // Even if you declared map with this line, you must use make to initialize map
|
|
m = make(map[string]FavoriteNumbers)
|
|
*/
|
|
m["Aliberk"] = FavoriteNumbers{1, 2, 3}
|
|
m["Deniz"] = FavoriteNumbers{4, 5, 6}
|
|
|
|
fmt.Println(m["Aliberk"])
|
|
|
|
var map2 map[int]int
|
|
// map2[5] = 1 // Runtime error without make: "panic: assignment to entry in nil map"
|
|
|
|
map2 = make(map[int]int)
|
|
|
|
map2[1] = 3
|
|
// map2["2"] = 1 // Compile error
|
|
map2['3'] = 1 // not 3, 51 (ASCII value)
|
|
|
|
fmt.Println(map2[5]) // any other non-declared value is zero
|
|
fmt.Println(map2[1])
|
|
fmt.Println(map2[3]) // 0
|
|
fmt.Println(map2[51]) // 1
|
|
fmt.Println(map2)
|
|
|
|
fmt.Printf("\nYou can also use Map Literals for assigning values directly, but keys are required!\n")
|
|
|
|
map3 := map[string]FavoriteNumbers{
|
|
"Prime": FavoriteNumbers{2, 3, 5}, // FavoriteNumbers are not necessary in there
|
|
"bigger": {123, 124, 125},
|
|
}
|
|
fmt.Println(map3)
|
|
fmt.Println(reflect.TypeOf(map3).Kind())
|
|
fmt.Println(reflect.TypeOf(map3["Prime"]).Kind())
|
|
fmt.Println(reflect.TypeOf(map3["Prime"].num1).Kind())
|
|
|
|
fmt.Printf("\n\n%p\n", map3)
|
|
fmt.Printf("%p\n", &map3)
|
|
|
|
fmt.Printf("\nElements can be deleted with delete function:\n")
|
|
delete(map3, "bigger")
|
|
fmt.Println(map3)
|
|
|
|
fmt.Println("Also Elements can be tested like this:")
|
|
elem, ok := map3["bigger"]
|
|
fmt.Println(elem, ok)
|
|
|
|
elem, ok = map3["Prime"]
|
|
fmt.Println(elem, ok)
|
|
|
|
}
|