go - 从 golang 中的嵌套映射中检索值

标签 go

我正在尝试从 map 中的 map 检索值。我遵循了在线教程,但没有得到正确的答案。这是我的程序:

type OptionMap map[string]interface{}
func(options OptionMap) {
    opt, _ := options["data2"].(OptionMap)
    fmt.Println("opt", opt)
    for key, value := range options {
        fmt.Println("Key:", key, "Value:", value)
    }
}

options 有两个键 data1 和 data2 。在 for 循环内部,printf 打印如下

Key: data1 Value: false
Key: data2 Value: map[h:5]

当我运行代码时

opt, _ := options["data2"].(OptionMap)

我在 opt 中得到了 nil。我不确定如何检索 map[h:5] 的值。

最佳答案

您正在为内部 map 获取 nil 值,因为您尚未使用类型 OptionMap 创建内部 map 。您必须使用 map[string]interface{} 创建它并尝试断言 OptionMap 无法获取 nil 值。请参阅下面的示例,该示例也与 OptionMap 类型一起使用。浏览类型断言页面 https://tour.golang.org/methods/15

package main

import "fmt"



type OptionMap map[string]interface{}

func main()  {
    opt := make(OptionMap)
    ineeropt := make(OptionMap)     // while creating Map specify OptionMap type
    ineeropt["h"]=5
    opt["data1"] = false
    opt["data2"] = ineeropt
    test(opt)


}
func test(options OptionMap) {
    opt, _ := options["data2"].(OptionMap)  //If inner map is created using OptionMap then opt won't be nil
    fmt.Println("opt", opt)
    fmt.Println("opt", options)
    for key, value := range options {
        fmt.Println("Key:", key, "Value:", value)
    }
}

关于go - 从 golang 中的嵌套映射中检索值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43358131/

相关文章:

go - 将例程与 channel 一起使用时出现死锁问题

amazon-web-services - 您如何在无服务器架构中平衡 nosql 存储和缓存?

python - WebSocket JWT Token 连接授权

javascript - AES CBC : JavaScript/CryptoJS Encrypt -> Golang Decrypt

go - Gin-Gonic v1.4.0 : ctx. FullPath() 缺失

database - GO 打开本地 postgres 连接

algorithm - 在 Go 中将 map 转换为树

Golang JSON 编码

go - golang 中是否有用于 int 参数 slice 或可变数量的 int 参数的内置 min 函数?

intellij-idea - go lang 项目的 intellij 未解析符号