https://play.golang.org/p/JGZ7mN0-U-
for k, v := range m {
fmt.Printf("key[%s] value[%s]\n", k, v)
}
or
for k := range m {
fmt.Printf("key[%s] value[%s]\n", k, m[k])
}
Go language specs for for statements specifies that the first value is the key, the second variable is the value, but doesn't have to be present.
https://play.golang.org/p/JGZ7mN0-U-
for k, v := range m {
fmt.Printf("key[%s] value[%s]\n", k, v)
}
or
for k := range m {
fmt.Printf("key[%s] value[%s]\n", k, m[k])
}
Go language specs for for statements specifies that the first value is the key, the second variable is the value, but doesn't have to be present.
Here's some easy way to get slice of the map-keys.
// Return keys of the given map
func Keys(m map[string]interface{}) (keys []string) {
for k := range m {
keys = append(keys, k)
}
return keys
}
// use `Keys` func
func main() {
m := map[string]interface{}{
"foo": 1,
"bar": true,
"baz": "baz",
}
fmt.Println(Keys(m)) // [foo bar baz]
}
Videos
I was working on some leetcode problems to practice go, bu I encountered a weird issue when I range over a map. I am not sure if it's a bug or a skill issue on my part (probably the 2nd)
type TreeNode struct{
Val int
Left *TreeNode
Right *TreeNode
}
func levelOrder(root *TreeNode) [][]int {
retMap := rec(root, 0)
var retList [][]int
for _, val := range retMap{
retList = append(retList, val)
}
return retList
}
func rec(root *TreeNode, level int) map[int][]int{
if root == nil{
return nil
}
retMap := make(map[int][]int)
retMap[level] = []int{root.Val}
leftMap := rec(root.Left, level+1)
rightMap := rec(root.Right, level+1)
for lvl := range leftMap{
retMap[lvl] = append(retMap[lvl], leftMap[lvl]...)
}
for lvl := range rightMap{
retMap[lvl] = append(retMap[lvl], rightMap[lvl]...)
}
return retMap
}
In the function `levelOrder` the order of val is random.
If the tree is:
0 --------1------- 1 ------2 - 3-----
Sometimes I get `[ [1], [2, 3] ]` and sometimes i get `[ [2, 3], [1] ]`
If i use
for i:=0; i<len(retMap); i++
as the bounds of the for loop, the values are return in the correct order.
Is this a skill issue on my part? Or is the range operator not supposed to be used like that?
Screen Shot of this in my terminal