映射动态值类型?

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

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


一只名叫tom的猫
浏览 61回答 1
1回答

江户川乱折腾

您可以将 as 用作interface{}映射的值,它将存储您传递的任何类型的值,然后使用类型断言来获取基础值。package mainimport (    "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")        }    }}游乐场上的工作代码接口类型的变量也有一个独特的动态类型,它是在运行时分配给变量的值的具体类型(除非该值是预先声明的标识符 nil,它没有类型)。动态类型在执行期间可能会发生变化,但存储在接口变量中的值始终可分配给变量的静态类型。var x interface{}  // x is nil and has static type interface{}var v *T           // v has value nil, static type *Tx = 42             // x has value 42 and dynamic type intx = 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")    }}您可以在开关盒中添加任意数量的类型以获取值
打开App,查看更多内容
随时随地看视频慕课网APP