Golang: convert []type to []interface

Eric
Oct 18, 2020

--

Below snippet is not allowed in golang:

func foo([]interface{}) { /* do something */ }

func main() {
var a []string = []string{"hello", "world"}
foo(a)
}
// can't use a type []string as type[]interface

Questing and the ans:

Gist

In Go, there is a general rule that syntax should not hide complex/costly operations. Converting a string to an interface{} is done in O(1) time. Converting a []string to an interface{} is also done in O(1) time since a slice is still one value. However, converting a []string to an []interface{} is O(n) time because each element of the slice must be converted to an interface{}.

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

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.

Main reason :

Convert []type to []interface is a O(n) complexity operation, which needs to be operated explicityly in golang!

Read more about generics in Golang: https://blog.golang.org/generics-next-step

--

--