From c027523355505992c535d6488545baf9172ece93 Mon Sep 17 00:00:00 2001 From: asandikci Date: Mon, 17 Jul 2023 09:13:08 +0300 Subject: [PATCH] Maps --- 2moretypes/maps.go | 67 ++++++++++++++++++++++++++++++++++++++++++++++ exercises/maps.go | 20 ++++++++++++++ 2 files changed, 87 insertions(+) create mode 100644 2moretypes/maps.go create mode 100644 exercises/maps.go diff --git a/2moretypes/maps.go b/2moretypes/maps.go new file mode 100644 index 0000000..3e9ed6c --- /dev/null +++ b/2moretypes/maps.go @@ -0,0 +1,67 @@ +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) + +} diff --git a/exercises/maps.go b/exercises/maps.go new file mode 100644 index 0000000..2c6d27e --- /dev/null +++ b/exercises/maps.go @@ -0,0 +1,20 @@ +package main + +// Exercise: https://go.dev/tour/moretypes/23 + +import ( + //"golang.org/x/tour/wc" // Not valid in local! + "strings" +) + +func WordCount(s string) map[string]int { + m := make(map[string]int) + for _, val := range strings.Fields(s) { + m[val] += 1 + } + return m +} + +func main() { + // wc.Test(WordCount) +}