I have this code:
type Iterable[T any] struct {
Val T
End T
Next func() (bool, T)
}
func acceptStructWithNext[T any](r struct{ Next func() (bool, T) }) {
fmt.Println(r)
}
func main() {
iterable := Iterable[int]{
Val: 0,
End: 100,
Next: func() (bool, int) {
return true, 0
},
}
acceptStructWithNext[int](iterable) // error is here
}
I get this compile error:
Cannot use 'iterable' (type Iterable[int]) as the type struct {...}
I thought structural typing was suppose to allow this type of thing - where did I go wrong?
Yes, but Go doesn't have "structural typing". To a certain degree the benefits of structural typing are available through the implicit satisfaction rules for interfaces. But this works for interface only.
See https://go.dev/doc/faq#implements_interface
By assuming Go would have textbook like structural typing for struct types.