This might be a bit silly and I apologize if it is but how do I guarantee that a field is defined in a struct before I can use it?
Let me explain this with example:
package main
import (
"fmt"
)
type animal struct {
name string
activity func()
}
var elephant = animal{
name: "elephant",
activity: func() {
fmt.Println("Eat grass")
fmt.Println("Stampede")
},
}
var lemur = animal{
name: "lemur",
activity: func() {
fmt.Println("Eat fruits")
fmt.Println("Climb trees")
},
}
func main() {
zoo := []animal{
elephant,
lemur,
// more goes here
}
for _, cage := range zoo {
cage.activity()
}
}
https://play.golang.org/p/0nXNk0DMuVd
Let's say there can be more animal
structs in zoo
array. Is there a better way to make sure that every animal must define activity
function other than doing the following:
for _, cage := range zoo {
if cage.activity != nil {
cage.activity()
}
}
Using method
doesn't look feasible here as implementation of activity
is quite different for each animal. I was also thinking of using interface
but then wouldn't I have to create a type of every animal?
The reason I'm not happy with the above if
solution is that the check is done in runtime only. However, if that's the only way to approach this problem then I'm okay with that too.