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

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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度