Home > Enterprise >  Golang - Cannot infer T...?
Golang - Cannot infer T...?

Time:09-05

Say I have the following code:

type Getter[T any] interface {
    Get() T
}

type Wrapper[T any] struct {
    a T
}

func (s Wrapper[T]) Get() T {
    return s.a
}

Here, you can say that Wrapper[T] implements Getter[T] - since it implements Get() T which is the only requirement.

Now, I have a function that needs to take a Getter[T] in order to return the internal value...

func Return[T any](i Getter[T]) T {
    return i.Get()
}

var s1 = Wrapper[int]{
    a: 5,
}

Here, Return just gets the value inside - so the expectation is that when I pass in s1, I should get 5 in return.

var s2 = Return(s1) // type Wrapper[int] of s1 does not match Getter[T] (cannot infer T)

...instead, I get that error. Now, there is an easy workaround here...

func (s Wrapper[T]) Getter() Getter[T] {
    return s
}

var s2 = Return(s1.Getter())

This ends up working. Getter() does nothing but return itself - functionally speaking, s1 and s1.Getter() should be identical here - and yet it doesn't work. T can be inferred in the method, but not as a parameter.

My question is this: Am I doing something wrong here - or is this just a part of Go? For this example to work, do I need to add a dummy method just to help the compiler - or am I missing something?

CodePudding user response:

You do not need to add methods to Wrapper, but if type inference does not succeed (the compiler can't infer all types), you have to provide the types for the type parameters explicitly, like this:

var s2 = Return[int](s1)

The Return() function has a type parameter, if you provide the type for T explicitly (int here), then the compiler will be able to validate that s1 does indeed implement the Getter[int] interface. Try it on the Go Playground.

  • Related