I would like to know why compiler refuse to compile
a function with a ...A defined parameters when I use []B... as argument
func WorkWithTypeA(lst ...A) {}
func main() {
listOfElementAsB := []B{&foo{wait:time.Duration(1*time.Second)},&foo{wait:time.Duration(1*time.Second)}}
WorkWithTypeA(listOfElementAsB... ) // <- not compile: cannot use listOfElementAsB (type []B) as type []A in argument to WorkWithTypeA
}
Because if I use only one parameter that work
func main() {
oneElementAsB:= B(&foo{wait:time.Duration(1*time.Second)})
WorkWithTypeA(oneElementAsB) // no complaine
}
The big issue with doing this is that []int and []interface{} have separate memory layouts, so you would need to copy the slice, which is better to do explicitly.
An even bigger issue if we allowed this:
func EditFirstElement(i ...interface{}) {
i[0] = "hello world"
}
func main() {
allTypes := []interface{}{5, 3+8i, "some more stuff"}
ints := []int{1, 2, 3, 4, 5}
EditFirstElement(allTypes...) // Actually changes the first element of allTypes to "hello world"
EditFirstElement(ints...) // uh oh...
}