A strange invalid recursive type error

Hi All,

I found a strange “invalid recursive type” compile error. The code will occur “invalid recursive type” error by run go build.

package main

func main() {
}

type A struct {
	i I
}

type B[T I] struct {
	i I
}

type I interface {
	funcA(*B[I])
}

When I change the declaration ordering, put B to the top, go build will work!
Is a go bug?

package main

func main() {
}

type B[T I] struct {
	i I
}

type A struct {
	i I
}

type I interface {
	funcA(*B[I])
}

Hi @jsc, welcome to the forum.

The generic definition of B is not necessary.
This compiles fine:

package main

func main() {
}

type A struct {
	i I
}

type B struct {
	i I
}

type I interface {
	funcA(*B)
}

(Also, struct B should use the type parameter T inside:

type B[T I] struct {
	i T
}

Although this does not change the error message.)

What do you want to achieve by parametrizing struct B?

1 Like

The “invalid recursive type” error occurs in your code because you have defined a recursive type in the interface declaration. In your example, the I interface refers to the B generic type parameter T, which in turn refers back to I, creating a recursive dependency.

To resolve this issue, you can modify your code by removing the recursive reference. Here’s an updated version of your code without the recursive type:

package main

func main() {
}

type A struct {
	i I
}

type B[T any] struct {
	i T
}

type I interface {
	funcA(*B[I])
}

In the updated code:

  • The generic type parameter T of the B struct is replaced with T any to allow any type to be used.
  • The I interface is defined as before, referring to *B[I] in the funcA method.

By removing the recursive dependency in the type definitions, you should no longer encounter the “invalid recursive type” error when building your code.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.