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 <https://goplay.tools/snippet/tFmC7rnFP3x> 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?

-- 
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 golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/1b01e1d8-0814-4a77-a67a-399f52da1ff4n%40googlegroups.com.

Reply via email to