实现说明
Map 双返回值区分缺失与零值可以归结为函数 main。
使用要点
- 跑完文件,输出里会留下标记——
apple:、pear:、kiwi:。
常见问题
运行「Map 双返回值区分缺失与零值」会打印什么?
运行文件本身,apple:、pear:、kiwi: 这些前缀各对应一段演示逻辑。
核心语句
quantity, ok := stock["apple"]
代码示例
package main
import "fmt"
func main() {
stock := map[string]int{
"apple": 0,
"pear": 12,
}
// ok separates a missing key from a key stored with its zero value
quantity, ok := stock["apple"]
fmt.Println("apple:", quantity, "present:", ok)
quantity, ok = stock["pear"]
fmt.Println("pear: ", quantity, "present:", ok)
quantity, ok = stock["kiwi"]
fmt.Println("kiwi: ", quantity, "present:", ok)
// check presence without writing a default into the map
if _, exists := stock["kiwi"]; !exists {
fmt.Println("kiwi is not stocked")
}
}