Answer the question
In order to leave comments, you need to log in
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
}
collection := new(Collection)
collection.Admin = User{"Alex"}
alex := User{"Alex"}
max := User{"Max"}
collection.People = []User{alex, max}
Answer the question
In order to leave comments, you need to log in
k.o. because they are different types)
play.golang.org/p/Wtat6zWKRC
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 questionAsk a Question
731 491 924 answers to any question