Golang: Cast array/slice of a type to array/slice of interface

Suppose you have this struct:

type (
    Type struct {
        X int

You want to convert this to an interface:

type (
    Interface interface {

You would do that in go in the following way:

t := Type{5}
var i Interface
i = t

Similarly, you would expect conversion of array/slice of Type to array/slice of Interface to work:

tlist := []Type{Type{0}, Type{1}}
var ilist []Interface
ilist = tlist

That would produce the following error:

cannot use tlist (type []Type) as type []Interface in assignment

Opps. So what happened?

The reason why Golang could not convert array/slice of a type to array/slice of an interface is clearly mentioned in the official FAQ. But this fact is very easy to miss if you are new to Golang.


Ravi Teja is a technology entrepreneur with interest in Embedded Systems, Software engineering, Operating Systems, Web development, Cloud computing, Machine learning, etc.

More Posts - Website

Follow Me:
LinkedInGoogle Plus