I
I
Igor2015-11-26 20:13:42
go
Igor, 2015-11-26 20:13:42

Why can't type []User be used as type []UserInterface?

play.golang.org/p/RKgQXPVGnb


type User struct {
Name string
}
func (u User) Say() {
fmt.Println(u.Name)
}
type UserInterface interface {
Say()
}
type Collection struct {
Admin UserInterface
People []UserInterface
}

It's right:

collection := new(Collection)
collection.Admin = User{"Alex"}

Then why is this wrong:

alex := User{"Alex"}
max := User{"Max"}
collection.People = []User{alex, max}

cannot use []User literal (type []User) as type []UserInterface in assignment

Answer the question

In order to leave comments, you need to log in

2 answer(s)
F
fastpars, 2015-11-26
@KorroLion

k.o. because they are different types)
play.golang.org/p/Wtat6zWKRC

T
Tyranron, 2015-11-26
@Tyranron

This is by design to avoid implicit expensive conversions.
The first thing to know is the difference between a "structure" and an "interface" in Go. It's simple, and it's enough to understand why you can't just "cast" a slice of structures into a slice of interfaces.
...
The second - and consonant with the above discussed slices - is that the operation of converting slices is an expensive operation. It's O(n) in time, and the Go compiler won't do such expensive things to keep careless programmers from writing slow code. If you want to do a potentially expensive operation - please, do it explicitly, all responsibility is on you, not on the compiler.
Read more:
Holivory article: reason #4
Explanation on SO

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question