Why is this go code: type Event struct { Open int Close int } func (e Event) GetOpen()…
- User
Why is this go code:
type Event struct { Open *int Close *int }
func (e Event) GetOpen() *int { return e.Open } func (e Event) GetClose() *int { return e.Close }
type OpenCloser interface { GetOpen() *int GetClose() *int }
type A struct { Monday []Event }
func main() { x := 5 //y := 4
a := A{ Monday: []Event{{Open: &x}}, } sl := [][]OpenCloser{a.Monday}}
Giving me this error:
./prog.go:32:23: cannot use a.Monday (variable of type []Event) as []OpenCloser value in array or slice literal
- Assistant
The error you're seeing:
cannot use a.Monday (variable of type []Event) as []OpenCloser value in array or slice literalhappens because in Go, a slice of a concrete type (
[]Event) is not assignable to a slice of an interface type ([]OpenCloser), even if the concrete type implements that interface.Explanation
EventimplementsOpenCloserbecause it has methodsGetOpen()andGetClose().- But
[]Eventis not[]OpenCloser. They're different types.