首页 > 解决方案 > ok 是什么意思 for 和 if 循环

问题描述

有人可以解释下面发生的事情吗?为什么以及何时在 for 循环中使用 ok?

distance := 0
for orbit, ok := orbits["ABC"]; ok; orbit, ok = orbits[orbit] {
    if _, ok := neworbits[orbit]; ok {
        fmt.Println(distance + neworbits[orbit])
        break
    }
    distance++
}

标签: go

解决方案


Map lookup has two forms:

x:=m[key]

This will lookup key in map m, and will return the corresponding value if it exists. If key does not exist, it will return the zero value for the value type.

x, ok=m[key]

This will also lookup key in map m, but will return (value,true) if the key exists, and (zero-value,false) if the key does not exist in the map.

In that example, ok will be true if the looked up key exists in the map.


推荐阅读