10. Go - Maps
Maps are key-value store. It's an un-ordered list.
Maps are a reference type meaning it will pass a reference of its values instead of a copy.
Creating maps:
var VARIABLE = map[KEY_TYPE]VALUE_TYPE{KEY_VALUE:VALUE_TYPE}
var map1 = map[string]int{}
var variable = make(map[string]int)
Getting value from map:
variable["KEY1"] = 50
variable2["KEY1"] = "KEY2"
Getting value and return whether found:
package main
import "fmt"
func main() {
var map1 = map[string]int{"TEST": 3}
v, ok := map1["TEST"]
fmt.Println(v, ok)
}
Getting value existence and acting upon true:
package main
import "fmt"
func main() {
var map1 = map[string]int{"TEST": 3}
if v, ok := map1["TEST"]; ok {
fmt.Println(v)
fmt.Println("exists")
}
}
Deleting key-value from map:
delete(mapvarable,KEY)
Iterating map:
package main
import "fmt"
func main() {
var map1 = map[string]int{
"TEST": 3,
"TEST2": 4,
}
for i, e := range map1 {
fmt.Println(i, "KEY")
fmt.Println(e, "VALUE")
}
}
Comments
Post a Comment