On Wed, Oct 31, 2018 at 11:21 AM <[email protected]> wrote:
> Hello, everyone.
> Consider following 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
>
> If I understand correctly it is because slice of interface type cannot be
> converted by the compiler to concrete type.
>
>
> What is correct way in golang to implement functionality that is presented in
> the example?
>
> When method argument defined using a slice of some interface, how I can pass
> it a slice of a concrete type that implements the interface?
>
>
You would end up needing to just do
func (p *phase) run(population {}interface) []data
and then type assert the {}interface into []implementation
There isn't a way to directly pass a slice of concrete type to a function
that accepts a slice of interface, unless you first do this:
iface := make([]data, len(population))
for i, p := range population {
iface[i] = p
}
MyPhase.run(iface)
Justin
> --
> You received this message because you are subscribed to the Google Groups
> "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to [email protected].
> For more options, visit https://groups.google.com/d/optout.
>
--
You received this message because you are subscribed to the Google Groups
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/d/optout.