quii / learn-go-with-tests

Learn Go with test-driven development
MIT License
22.2k stars 2.81k forks source link

Generics chapter: example for calling a function with a type that cannot be inferred #770

Open VillePuuska opened 5 months ago

VillePuuska commented 5 months ago

In the Generics chapter, could we add an example showing how to call a function with a type parameter that cannot be inferred? Specifically, this happens when a function returns a value with a type that cannot be inferred from its parameters. I wondered about this when playing with generics after reading the chapter. Gopls showed me how to do it, but I think adding an example of this to the book could be helpful.

For a concrete example, we could add a constructor for the type Stack[T] introduced in the chapter:

func NewStack[T any]() *Stack[T] {
    return new(Stack[T])
}

which requires the type T to be specified when calling, e.g.:

stringStack := NewStack[string]()
intStack := NewStack[int]()

This example could be added to the end of the section Next: Generic data types.

If this sounds good to you, I'd be happy to write it and make a PR.

quii commented 4 months ago

Yeah go for it!