【发布时间】:2018-10-28 20:02:46
【问题描述】:
在 Go 语言中, 我正在尝试将接口转换为字节片。 调试器清楚地表明它是一个字节切片。
// 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
}
当我检查了 Interface 的 Type 是 Slice 并且 Sub-Item 的 Type 是 Uint8 时,我会执行 Type Assertion。但由于某种原因,它失败了。怎么可能?
“ok”变量变为“false”后的 GoLand 调试器屏幕截图: http://imagehost.cc/image/v4403
谢谢!
【问题讨论】:
标签: go types casting slice assertion