dictionary - 映射动态值类型?

标签 dictionary go dynamic interface

有什么方法可以创建具有动态值类型的映射,以在单个映射中同时存储浮点值和字符串值?

myMap["key"] = 0.25
myMap["key2"] = "some string"

最佳答案

您可以使用 interface{} 作为映射的值,它将存储您传递的任何类型的值,然后使用类型断言获取基础值。

package main

import (
    "fmt"
)

func main() {
    myMap := make(map[string]interface{})
    myMap["key"] = 0.25
    myMap["key2"] = "some string"
    fmt.Printf("%+v\n", myMap)
    // fetch value using type assertion
    fmt.Println(myMap["key"].(float64))
    fetchValue(myMap)
}

func fetchValue(myMap map[string]interface{}){
    for _, value := range myMap{
        switch v := value.(type) {
            case string:
                fmt.Println("the value is string =", value.(string))
            case float64:
                fmt.Println("the value is float64 =", value.(float64))
            case interface{}:
                fmt.Println(v)
            default:
                fmt.Println("unknown")
        }
    }
}

Playground 上的工作代码

Variables of interface type also have a distinct dynamic type, which is the concrete type of the value assigned to the variable at run time (unless the value is the predeclared identifier nil, which has no type). The dynamic type may vary during execution but values stored in interface variables are always assignable to the static type of the variable.

var x interface{}  // x is nil and has static type interface{}
var v *T           // v has value nil, static type *T
x = 42             // x has value 42 and dynamic type int
x = v              // x has value (*T)(nil) and dynamic type *T

如果您不使用 switch 类型来获取值:

func question(anything interface{}) {
    switch v := anything.(type) {
        case string:
            fmt.Println(v)
        case int32, int64:
            fmt.Println(v)
        case SomeCustomType:
            fmt.Println(v)
        default:
            fmt.Println("unknown")
    }
}

您可以在 switch case 中添加任意数量的类型来获取值

关于dictionary - 映射动态值类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52454489/

相关文章:

go - 在 Golang 当前演示文稿中编辑 .play 代码部分

go - 如何从变量分配结构的字段名称

python - 我可以像 python 中的字典引用一样对对象进行可变化吗

go - 从 golang 使用 AMQP 1.0 连接到 IBM MQ 时出现 EOF

multithreading - 在错误组中运行多个服务器的问题

javascript - mwlresizable 不起作用

go - 如何在 Golang 中动态映射数据库表?

dictionary - 为什么 Map 不适用于 Groovy 中的 GString?

c# - 仅在 Visual Studio 的调试器中按键对字典进行排序

java - 使用相同的键订购 map