go - 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++
}
解决方案
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.
推荐阅读
- google-cloud-platform - 在 Google Cloud 中集群 Eureka 服务器
- excel - 搜索多个条件时 Excel 替代 FIND 函数
- rest - APIRestful 中的资源
- javascript - 不能使用 for 循环来填充完整日历中的数组
- sql - 子查询不起作用,但手动输入可以
- arrays - 从 JSON 数组中提取数据以创建 3 个不同的数组
- swift4 - CollectionViewController 不会显示我的文本
- perl - 使用带有空格的变量 Perl
- asp.net-mvc - Azure Web App 在空闲 4 分钟内获得时间
- react-native - 在 React Native 中保存数据并发送到另一个类