Golang中的Switch i.(type)返回的类型与reflect.TypeOf()返回的类型不同。

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

Golang Switch i.(type) returning different type than reflect.TypeOf()

问题

我有这个函数,它返回不同的类型。

这是 playground 的链接 https://play.golang.org/p/ErNt-rJTEbz

package main

import (
	"fmt"
	"reflect"
)

func main() {
	a := []uint8{24, 12}
	var b interface{} = a
	
	fmt.Println(reflect.TypeOf(b)) // []uint8
	switch b.(type) {
	case []byte:
		fmt.Println("is byte")
	}
}

// 输出: is byte
英文:

I have this function and it's returning different type.

Here's the playground link https://play.golang.org/p/ErNt-rJTEbz

package main

import (
	"fmt"
	"reflect"
)

func main() {
	a := []uint8{24, 12}
	var b interface{} = a
	
	fmt.Println(reflect.TypeOf(b)) // []uint8
	switch b.(type) {
	case []byte:
		fmt.Println("is byte")
	}
}

// output: is byte

答案1

得分: 4

byteuint8 的别名。尝试运行以下代码,它将显示错误信息:

switch b.(type) {
case []byte:
    fmt.Println("是 byte")
case []uint8:
    fmt.Println("是 uint8")
}

错误信息为:在类型开关语句中有重复的 case []uint8

英文:

byte is an alias of uint8. Try this, and it will show the error:

	switch b.(type) {
	case []byte:
		fmt.Println("is byte")
	case []uint8:
		fmt.Println("is uint8")
	}

duplicate case []uint8 in type switch

huangapple
  • 本文由 发表于 2021年10月2日 00:42:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/69409365.html
匿名

发表评论

匿名网友

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

确定