package main
import (
"fmt"
)
func main() {
var a A
var b B
for _, v := range []WhatAreYou{a, b} {
fmt.Println(v.Question())
}
}
type WhatAreYou interface {
Question() string
}
type A struct {
string
}
type B struct {
int
}
func (a A) Question() string {
return "I'm an A"
}
func (b B) Question() string {
return "I'm a B"
}
The code above works as I expect and calls the function on each interface as expected. Go Play
In my actual code I intend to have many different types implementing an interface. How can I get rid of the var a A var b B etc and simply declare them all in the slice? i.e. I tried and failed with the following and other variations
for _, v := range []WhatAreYou{a A, b B} {
[]WhatAreYou{A{}, B{}}
This is correct, thanks to mkopriva. Composite Literals
Now I understand a little better what I am doing here I think I understand why this question is down voted too. The question doesn't really make sense. I was so hung up on the idea of the interface I didn't think of anything else. var a A is declaring a struct that happens to implement an interface. This is even more obvious if you initialise the struct e.g. var a = A{"hello"} or inline A{"hello"}, B{2}