douxing2156 2018-11-12 11:32
浏览 33
已采纳

反映类型比较

I want to ensure that the type of map keys is string. Key() method returns Type and I'm not sure what is the right way to check if it's string. The only thing came to my mind is:

if v.Type().Key() == reflect.TypeOf("") {
    fmt.Print("It is string")
}

Is it the right way?

  • 写回答

2条回答 默认 最新

  • dotaer1993 2018-11-12 11:59
    关注

    Yes, what you did reports if the key type is "exactly" string.

    But for example if the key type would be a custom type having string as its underlying type, like in this example:

    type mystr string
    m := map[mystr]int{}
    

    Then the key type would not be equal to reflect.TypeOf("").

    It's up to you if this is what you want. If you do want to accept the above map types too, you may check the kind of the key if it equals to reflect.String like this:

    if v.Type().Key() == reflect.TypeOf("") {
        fmt.Print("It is string")
    }
    
    if v.Type().Key().Kind() == reflect.String {
        fmt.Print("It is string kind")
    }
    

    For the above map[mystr]int, this is the output (try it on the Go Playground):

    It is string kind
    

    (The key is not of type string, but it is of kind string.)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错
  • ¥20 @microsoft/fetch-event-source 流式响应问题