英文:
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
byte 是 uint8 的别名。尝试运行以下代码,它将显示错误信息:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论