Why can't I concationate two slices of an interface and implemetation?

123 views
Skip to first unread message

Ian Spence

unread,
Jun 18, 2024, 8:43:46 PM (11 days ago) Jun 18
to golang-nuts
Hi all!

I've encountered a limitation and I'd like to understand what's going on and why it's not working the way I would expect.

If I have a slice of an interface type, and another slice of a type that implements that interface, I cannot concat these slices together using append - but I can add each item one by one.

I would expect that interface implementations would also apply to slices, but it looks like it doesn't?

Here's the brief example: https://go.dev/play/p/sWFKeVfSOkW

package main

type IExample interface {
Foo() string
}

type TBar struct{}

func (t TBar) Foo() string {
return ""
}

func main() {
examples := []IExample{}
bars := []TBar{TBar{}, TBar{}}

// Works
for _, bar := range bars {
examples = append(examples, bar)
}

// Does not work
examples = append(examples, bars...)
// ./prog.go:23:30: cannot use bars (variable of type []TBar) as []IExample value in argument to append
}


Ian Lance Taylor

unread,
Jun 18, 2024, 8:53:09 PM (11 days ago) Jun 18
to Ian Spence, golang-nuts
On Tue, Jun 18, 2024 at 5:43 PM Ian Spence <ian.d....@gmail.com> wrote:
>
> I've encountered a limitation and I'd like to understand what's going on and why it's not working the way I would expect.
>
> If I have a slice of an interface type, and another slice of a type that implements that interface, I cannot concat these slices together using append - but I can add each item one by one.
>
> I would expect that interface implementations would also apply to slices, but it looks like it doesn't?

That is correct. The language permits implicitly converting a single
value to an interface type. It does not permit implicitly converting
a slice of some type to a slice of some interface type. See the FAQ
entry https://go.dev/doc/faq#convert_slice_of_interface .

Ian
Reply all
Reply to author
Forward
0 new messages