On Sat, 2023-10-21 at 11:58 -0700, Mike Schinkel wrote:
> Recently I was trying to write a func using generics where I wanted
> to use a slice of an interface that would contain implementers of
> that interface and then pass those types to a generic function, but I
> ran into this error:
>
> type MyStruct of MySlice{} does not match inferred type MyInterface
> for T
>
> My code is complex so I wrote the simplest example for this email and
> here is part of that code:
>
> type Suiter interface {
> Suit()
> }
> func Append[T any](s []T, i T) []T {
> return append(s, i)
> }
> func main() {
> var s []Suiter
>
> //CAN GENERICS SUPPORT THIS?
> //s = Append(s, Clubs{})
> //s = Append(s, Hearts{})
> //s = Append(s, Diamonds{})
> //s = Append(s, Spades{})
>
> //VERSUS HAVING TO DO THIS?
> s = Append(s, Suiter(Clubs{}))
> s = Append(s, Suiter(Hearts{}))
> s = Append(s, Suiter(Diamonds{}))
> s = Append(s, Suiter(Spades{}))
>
> for _, suit := range s {
> fmt.Printf("Suit: %s\n", suitName(suit))
> }
> }
> The full code is here in a playground.
>
> Note: My example func Append() makes no sense in real use, I only use
> it as it should be an easily understood example to show the syntax I
> am trying to illustrate.
>
> Question: Is there a way to write Append() such that I can call
> Append(s, Clubs{}) instead of having to write Append(s,
> Suiter(Clubs{}))?
>
> And if no, is there a chance that in the future Go generics will be
> able to support that level of type inference?
>
The pre-generics language handles this case:
https://go.dev/play/p/jaJF7LTSVYe
Is there something about your real case that makes this not acceptable?
--
You received this message because you are subscribed to the Google Groups
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/golang-nuts/9aab12f4935edebe2067bbae3c00faa5b50c79d8.camel%40kortschak.io.