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

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

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

问题

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

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

  1. package main
  2. import (
  3. "fmt"
  4. "reflect"
  5. )
  6. func main() {
  7. a := []uint8{24, 12}
  8. var b interface{} = a
  9. fmt.Println(reflect.TypeOf(b)) // []uint8
  10. switch b.(type) {
  11. case []byte:
  12. fmt.Println("is byte")
  13. }
  14. }
  15. // 输出: is byte
英文:

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

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

  1. package main
  2. import (
  3. "fmt"
  4. "reflect"
  5. )
  6. func main() {
  7. a := []uint8{24, 12}
  8. var b interface{} = a
  9. fmt.Println(reflect.TypeOf(b)) // []uint8
  10. switch b.(type) {
  11. case []byte:
  12. fmt.Println("is byte")
  13. }
  14. }
  15. // output: is byte

答案1

得分: 4

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

  1. switch b.(type) {
  2. case []byte:
  3. fmt.Println("是 byte")
  4. case []uint8:
  5. fmt.Println("是 uint8")
  6. }

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

英文:

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

  1. switch b.(type) {
  2. case []byte:
  3. fmt.Println("is byte")
  4. case []uint8:
  5. fmt.Println("is uint8")
  6. }
  7. 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:

确定