将”reflect”转化为可比较的数据。

huangapple go评论73阅读模式
英文:

turn reflect into comparable data

问题

我想要使用reflect来比较对象的类型。以下是我的代码:

package main

import (
	"fmt"
	"reflect"
)

func main() {
	tst := "cat"
	if reflect.TypeOf(tst).Kind() == reflect.String {
		fmt.Println("It's a string!")
	}
}

这样会给我一个错误提示type string is not an expression。我该如何只使用 reflect来修复这个问题?(不使用类型切换等其他方法)

英文:

I want to be able to compare the type of an object using reflect. Here is my code:

package main

import (
	"fmt"
	"reflect"
)

func main() {
	tst := "cat"
	if reflect.TypeOf(tst) == string {
		fmt.Println("It's a string!")
	}

}

This gives me an error type string is not an expression. How can I fix this only using reflect? (no type switches, etc.)

答案1

得分: 2

两个简单的选项:

使用Kind

if reflect.TypeOf(tst).Kind() == reflect.String {
    fmt.Println("It's a string!")
}

使用TypeOf另一个字符串:

if reflect.TypeOf(tst) == reflect.TypeOf("") {
    fmt.Println("It's a string!")
}

然而,个人而言,我更喜欢使用类型切换或类型检查(即if _, ok := tst.(string); ok {...})。

英文:

Two simple options:

use Kind:

if reflect.TypeOf(tst).Kind() == reflect.String {
    fmt.Println("It's a string!")
}

use TypeOf another string:

if reflect.TypeOf(tst) == reflect.TypeOf("") {
    fmt.Println("It's a string!")
}

However, personally I'd prefer a type switch or type check (i.e. if _, ok := tst.(string); ok {...}

huangapple
  • 本文由 发表于 2016年2月21日 22:05:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/35537094.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定