登录
首页 >  Golang >  Go问答

映射中包含动态值类型

来源:stackoverflow

时间:2024-03-01 22:27:26 385浏览 收藏

从现在开始,努力学习吧!本文《映射中包含动态值类型》主要讲解了等等相关知识点,我会在golang学习网中持续更新相关的系列文章,欢迎大家关注并积极留言建议。下面就先一起来看一下本篇正文内容吧,希望能帮到你!

问题内容

有没有办法创建具有动态值类型的映射,以便在单个映射中存储浮点值和字符串值?

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 上的工作代码

接口类型的变量也有一个独特的动态类型, 是运行时赋给变量的值的具体类型 (除非该值是预先声明的标识符 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

如果您不使用该类型,请使用开关来获取值:

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 中添加任意数量的类型来获取值

好了,本文到此结束,带大家了解了《映射中包含动态值类型》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>