du131642 2018-09-22 07:26
浏览 34
已采纳

映射为动态值类型?

Is there any way to create a map with a dynamic value type, to store in a single map both float and string values?

myMap["key"] = 0.25
myMap["key2"] = "some string"
  • 写回答

1条回答 默认 最新

  • duancha1065 2018-09-22 07:28
    关注

    You can use interface{} as the value for the map which will store any type of value you pass and then use type assertion to fetch the underlying value.

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        myMap := make(map[string]interface{})
        myMap["key"] = 0.25
        myMap["key2"] = "some string"
        fmt.Printf("%+v
    ", 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")
            }
        }
    }
    

    Working code on 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
    

    If you do not the type use switch to fetch the value as:

    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")
        }
    }
    

    you can add as many types you want in the switch case to get the value

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题