3

code:

package main

import "fmt"

type implementation struct {
    d []int
}

func (impl *implementation) getData() interface{} {
    return impl.d
}

type phase struct{}

type data interface {
    getData() interface{}
}

func MakeIntDataPhase() *phase {
    return &phase{}
}

func (p *phase) run(population []data) []data {
    return nil
}

func main() {
    var population []implementation
    MyPhase := MakeIntDataPhase()
    fmt.Println(MyPhase.run(population))

}

When running following code in playground I got following error: prog.go:30:25: cannot use population (type []implementation) as type []data in argument to MyPhase.run

I am new to golang and I don't understand why is this happening?

Struct implementation implements method getData() from data interface. Isn't it enough to use a slice of implementation in run method?

Where my reasoning is wrong?

1

1 Answer 1

4

This seems counter-intuitive but []data is of a different type to []implementation because of how slice types are represented in Go.

This is actually discussed in the the Go Wiki

Edit: Consider this

var impl []*implementation
var data []data = impl

The compiler will complain with

cannot use impl (type []*implementation) as type []data in assignment

It's more code but you actually have to create a slice of your interface as what the comments in this thread recommends, like so:

var impl []*implementation
var data []data

// assuming impl already has values
for _, v := range impl {
    data = append(data, v)
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.