[英]Golang Type Assertion Failure
In Golang, I am trying to convert an Interface to Slice of Bytes. 在Golang中,我试图将接口转换为字节片。 Debugger clearly shows that it is a Slice of Bytes.
调试器清楚地表明它是一个字节片。
// Check an Interface's Type.
ifcType = reflect.TypeOf(ifc).Kind()
// Array?
if ifcType == reflect.Slice {
// Get Type of Sub-Elements.
ifcElementType = reflect.TypeOf(ifc).Elem().Kind()
if ifcElementType == reflect.Uint8 {
// Array of Bytes.
// => 'bencode' Byte String.
// Convert the Type.
ba, ok = ifc.([]byte)
if !ok {
return nil, ErrTypeAssertion
}
When I have checked that Interface's Type is Slice and Sub-Item's Type is Uint8, I do the Type Assertion. 当我检查接口的类型为Slice且子项的类型为Uint8时,我执行类型声明。 But for some Reason, it fails.
但是由于某种原因,它失败了。 How can that be ?
怎么可能 ?
GoLand's Debugger Screenshot just after 'ok' Variable has become 'false': http://imagehost.cc/image/v4403 刚好在“ ok”变量变为“ false”之后的GoLand的调试器屏幕截图: http : //imagehost.cc/image/v4403
Thank you! 谢谢!
I have found the Reason. 我找到了原因。
That Slice of Bytes was really of 'ByteString' Type which really was a Slice of Bytes. 该字节切片实际上是“ ByteString”类型,而实际上是“字节切片”。 Why the Compiler does not understand that these are equal Types I can not understand.
为什么编译器不理解这些是我无法理解的相等类型。
I had to change the Field's Type from a Type Alias to simple '[]byte', and it now works. 我不得不将字段的类型从类型别名更改为简单的[[byte],现在可以使用了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.