简体   繁体   English

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

[英]how to use reflect.TypeOf([]string{“a”}).Elem()?

I'm really new to golang and I'm struggling with the basics. 我真的是golang的新手,我在基础方面苦苦挣扎。 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) 无效的操作:reflect.TypeOf([]字符串文字).Elem()== reflect.String(类型不匹配的reflect.Type和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" 我不了解文档https://golang.org/pkg/reflect/,因为我找不到有关如何引用不同“类型”或“种类”的示例

How should I be writing my if statements to do the comparisons I'm attempting? 我应该如何编写我的if语句来进行比较?

reflect.Type is an interface with a method called Kind() . reflect.Type是带有Kind()方法的interface 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")
}

To compare types, use: 要比较类型,请使用:

if reflect.TypeOf([]string{"a"}).Elem() == reflect.TypeOf("") {
  log.Println("success")
}

To compare kinds, use: 要比较种类,请使用:

if reflect.TypeOf([]string{"a"}).Elem().Kind() == reflect.String {
  log.Println("success")
}

If you want to test for a specific type, then compare types. 如果要测试特定类型,请比较类型。 If you want to determine what sort of type it is, then compare kinds. 如果要确定它是哪种类型,请比较种类。

This example might help: 该示例可能会有所帮助:

type x string

The x and string types are both kinds of string. xstring类型都是字符串。 The kind comparison returns true for both: 两者的种类比较均返回true:

fmt.Println(reflect.TypeOf(x("")).Kind() == reflect.String) // prints true
fmt.Println(reflect.TypeOf("").Kind() == reflect.String) // prints true

The x and string types are distinct: xstring类型是不同的:

fmt.Println(reflect.TypeOf(x("")) == reflect.TypeOf(""))    // prints false

For simple type comparisons like what you're showing, you don't need reflection. 对于简单的类型比较(如您所显示的内容),您无需进行反思。 You can use a type assertion instead: 您可以改用类型断言

stuff := []interface{}{"hello", 1, nil}
for _, obj := range stuff {
        if _, ok := obj.(string); ok {
                fmt.Printf("is a string\n")
        } else if _, ok := obj.(int); ok {
                fmt.Printf("is an int\n")
        } else {
                fmt.Printf("is something else\n")
        }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM