Cannot use struct as the type struct {...}

214 views Asked by At

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?

2

There are 2 answers

1
Volker On BEST ANSWER

I thought structural typing was suppose to allow this type of thing [...]

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

[...] where did I go wrong?

By assuming Go would have textbook like structural typing for struct types.

3
Gortameyer On

struct {Val int; End int; Next func() (bool, int)} and struct{ Next func() (bool, int) } and are different types. The first has Val and End fields. The second does not.