神秘的类型断言失败?

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

Mysterious type assertion failure?

问题

在什么情况下,这段代码会产生带有消息 panic: NOPE int64 的 panic?

这是一个错误吗?还是我对数字类型的一些基本知识有所遗漏?

英文:

Under what circumstances could this code:

		v, ok := value.(int64)
		if !ok  {
			panic("NOPE "+reflect.TypeOf(value).Kind().String())
		} else {
			fmt.Printf("VAL: %d\n",v)
		}

produce the panic with message panic: NOPE int64?

Is this a bug or is there something basic about the numeric types that I'm missing?

答案1

得分: 4

这可能是因为你在数字类型上使用了类型声明。如果你像这样做:

type T int64 

...

var value interface{} = T(1)

并将其放入你的代码中,你将得到完全相同的错误。但是,如果你不检查kind,而是检查类型,你将看到这里发生了什么:

v, ok := value.(int64)
if !ok {
	panic("NOPE " + reflect.TypeOf(value).String())
} else {
	fmt.Printf("VAL: %d\n", v)
}

会产生以下消息:

panic: NOPE main.T

T的kind是int64,但value并不是int64。

英文:

This can happen if you're using type declaration on numeric types. If you do something like this:

type T int64 

...

var value interface{} = T(1)

and put it into your code, you'll get the exact same error. But if you don't check the kind, but the type, you'll see what's happening here:

v, ok := value.(int64)
if !ok {
	panic("NOPE " + reflect.TypeOf(value).String())
} else {
	fmt.Printf("VAL: %d\n", v)
}

produces the message:

panic: NOPE main.T

The kind of T is int64, but value is not int64.

huangapple
  • 本文由 发表于 2015年5月16日 04:35:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/30268300.html
匿名

发表评论

匿名网友

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

确定