使用动态值类型映射?

Mar*_*tin 4 dictionary interface dynamic go

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

myMap["key"] = 0.25
myMap["key2"] = "some string"
Run Code Online (Sandbox Code Playgroud)

Him*_*shu 6

您可以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")
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Playground 上的工作代码

接口类型的变量也有一个独特的动态类型,它是在运行时分配给变量的值的具体类型(除非该值是预先声明的标识符 nil,它没有类型)。动态类型在执行期间可能会有所不同,但存储在接口变量中的值始终可以分配给变量的静态类型。

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
Run Code Online (Sandbox Code Playgroud)

如果您不使用 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")
    }
}
Run Code Online (Sandbox Code Playgroud)

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