doujieyu7062 2014-02-01 08:22 采纳率: 0%
浏览 207
已采纳

Golang如何为未知接口进行类型断言?

I understand that I can get an object's value by reflection and then use type assertion to get back the actual object using:

obj := new(User)
out := reflect.ValueOf(obj).Elem().Interface().(User)
fmt.Println(out == *obj) // true

But what if I don't know that the object's type is User, how can I do type assertion? Say it was inside a function like:

func Foo(obj interface{}) bool {
    // out := reflect.ValueOf(obj).Elem().Interface().( ... )
    return out == *obj
}

func main() {
    obj := new(User)
    fmt.Println(Foo(obj))
}

Inside the Foo function you'll never know what type of object will actually be passed and so how do you complete the type assertion?

  • 写回答

1条回答 默认 最新

  • douchao0358 2014-02-01 09:33
    关注

    You can't. Type assertions allow you to take advantage of the static type checking that the language gives you even if you have an interface, whose type isn't statically checked. It basically works something like this:

    You have some statically typed variable s, which has type t. The compiler enforces the guarantee that s always has type t by refusing to compile if you ever try to use s as if it were a different type, since that would break the guarantee.

    You also have some interface variable, i. i's type is not known at compile-time, so there's no way the compiler can guarantee that assigning i to s wouldn't break the guarantee that s had type t. However, what you can do is a type assertion. A type assertion side-steps this problem by saying, "well, I'll check at run-time, and I'll only do the assignment if the types match up." The compiler is OK with this because it knows that the assignment will only happen if the types match up, which means that it can still guarantee that s has type t. So basically what's happening at runtime is:

    if (i has type t) {
        s = i
    } else {
        s = t{} // Zero value of t
    }
    

    The reason that what you're asking for is impossible is that the compiler has to know what type you're checking against so that it can write the check that I gave pseudocode for above. Without knowing what t is, there's no way to know what the static type of s should be, and no way to check whether it's right.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?