Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Golang – Cannot infer T…?

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…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading