3

I'm refactoring some of my code now that Go 1.18 is out with the new Generics feature. I've created a generic interface i.e

type IExample[T any] interface{
    ExampleFunc(ex T) T
}

Somewhere in my code, I want to store several implementations of this interface in a map and use them generically in my code.

mapping := map[string]IExample{
        // .......
}

But the go compiler throws this error cannot use generic type types.SettingsAdapter[T any] without instantiation

So, I tried adding any to the generic type

mapping := map[string]IExample[any]{
        // .......
}

Which resulted in the following error

IExample[any] does not implement IExampleImpl[ExampleT]

At this point, I feel that there's something I'm missing while implementing the code, or that I'm just using this feature in a way that it wasn't meant to be used.

Thanks :)

Ori Zerah
  • 89
  • 1
  • 7
  • 3
    `any` is the same as `interface{}`, i.e. the empty interface. When you instantiate a `IExample` with `any`, the only values you can then assign to it are **exactly** those that implement `IExample[any]`, i.e. have method `ExampleFunc(ex any) any` – blackgreen Mar 30 '22 at 12:56
  • 4
    cont: different instances of `IExample[T]` are different types altogether. If you want to declare *a single variable* that can hold arbitrary instances of `IExample[T]` you are back to `map[string]any` – blackgreen Mar 30 '22 at 12:59
  • 1
    What are `IExampleImp` and `ExampleT`? They're declared nowhere in your code. Also, the `I` prefix in interface name is not welcome in Go :) – jub0bs Mar 31 '22 at 06:33

0 Answers0