【问题标题】:Golang Type Assertion FailureGolang 类型断言失败
【发布时间】: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


    【解决方案1】:

    我找到了原因。

    那个 Slice of Bytes 实际上是 'ByteString' 类型,它确实是一个 Slice of Bytes。 为什么编译器不理解这些是相等的类型我无法理解。

    我必须将字段的类型从类型别名更改为简单的“[]byte”,现在它可以工作了。

    【讨论】:

    • 当时大概不是类型别名。