drjmrg8766 2018-07-08 04:40
浏览 611
已采纳

如何使用reflect.TypeOf([] string {“ a”})。Elem()?

I'm really new to golang and I'm struggling with the basics. I wrote a piece of code like this:

package main
import (
  "log"
  "reflect"
)

if reflect.TypeOf([]string{"a"}).Elem() == reflect.String {
  log.Println("success")
}
if reflect.TypeOf([]int{1}).Elem() == reflect.Int{
  log.Println("success")
}
if reflect.TypeOf([]float64{1.00}).Elem() == reflect.Float64 {
  log.Println("success")
}

When I run this code, I get the error

invalid operation: reflect.TypeOf([]string literal).Elem() == reflect.String (mismatched types reflect.Type and reflect.Kind)

I don't understand the documentation https://golang.org/pkg/reflect/ because I can't find examples of how to reference the different "types" or "kinds"

How should I be writing my if statements to do the comparisons I'm attempting?

  • 写回答

3条回答 默认 最新

  • doudou201701 2018-07-08 04:43
    关注

    reflect.Type is an interface with a method called Kind(). As per document:

        // Kind returns the specific kind of this type.
        Kind() Kind
    

    So you should write :

    if reflect.TypeOf([]string{"a"}).Elem().Kind() == reflect.String {
      log.Println("success")
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记