Type converting slices of interfaces

后端 未结 6 1739
孤街浪徒
孤街浪徒 2020-11-22 04:04

I\'m curious why Go does\'t implicitly convert []T to []interface{} when it will implicitly convert T to interface{}. Is

6条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 04:40

    The thing you are missing is that T and interface{} which holds a value of T have different representations in memory so can't be trivially converted.

    A variable of type T is just its value in memory. There is no associated type information (in Go every variable has a single type known at compile time not at run time). It is represented in memory like this:

    • value

    An interface{} holding a variable of type T is represented in memory like this

    • pointer to type T
    • value

    So coming back to your original question: why go does't implicitly convert []T to []interface{}?

    Converting []T to []interface{} would involve creating a new slice of interface {} values which is a non-trivial operation since the in-memory layout is completely different.

提交回复
热议问题