michaelsnowden
michaelsnowden

Reputation: 6202

Assign to list of interfaces in Go

I have an interface Foo with a struct foo that implements it. I have an API that accepts a list of Foos, and I need to pass in my list of foos, but it doesn't work as expected:

package main

import "fmt"

type foo struct {
}

func (f foo) Do() {
    fmt.Println("hi")
}

type Foo interface {
    Do()
}

func main() {
    var f foo
    var F Foo
    F = f // compiles just fine
    var fs []foo
    var Fs []Foo
    Fs = fs // doesn't compile for some reason
}

I'm sure I'm missing something obvious as I'm very new to Go, but why doesn't this compile?

Upvotes: 1

Views: 2485

Answers (1)

nneonneo
nneonneo

Reputation: 179552

A slice of interfaces is not an interface - the layout of an interface and the layout of a concrete structure are different. Therefore, you can't assign []foo to []Foo.

This is a common enough error that it's even documented on the golang wiki: https://github.com/golang/go/wiki/InterfaceSlice

If you need a slice of Foo interfaces then you'll have to just make one and assign them in a loop. Example taken from the wiki:

var dataSlice []int = foo()
var interfaceSlice []interface{} = make([]interface{}, len(dataSlice))
for i, d := range dataSlice {
    interfaceSlice[i] = d
}

Upvotes: 5

Related Questions