> https://go.dev/play/p/h5jzISRyTkF In this approach, I'm not fond of how I must call the f function on line 30. Without specifying a type parameter, the call fails to compile.
If I replace f[A](a, "") with f(a, "") it still works for me, in the playground. What go version are you using? There were several improvements to type inference for generics in 1.21. https://tip.golang.org/doc/go1.21#language On Sunday, 10 September 2023 at 01:17:55 UTC+1 Oleh Lomaka wrote: > Hello everybody, > > Gophers' superpower is required and highly appreciated. > > I have two types, A and B, each of which has a method named "M". This > method accepts a string and returns an instance of the type it is declared > on. > > ```go > type A struct {} > func (a A) M (string) A { > return a > } > type B struct {} > func (b B) M (string) B { > return b > } > ``` > What's the best way to declare a generic function that receives an > instance of one of these types along with a string? Depending on the > string, this function should either return the instance it received or call > method M on it and return the instance produced by this method. > > Currently, I've come up with two solutions, but I'm not entirely satisfied > with either: > > https://go.dev/play/p/h5jzISRyTkF In this approach, I'm not fond of how I > must call the f function on line 30. Without specifying a type parameter, > the call fails to compile. Additionally, I'm concerned about potential > panics on line 23. If I expand the code with new types in the future, > there's a risk of type assertion failures. > > https://go.dev/play/p/rHHjV_A-hvK While this solution appears cleaner, > it's prone to panicking if I introduce another type with an incompatible M > signature (or without M method completely) > > Maybe someone has better ideas. > > Thank you. > All the best, > -- 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/967a1949-eae2-4920-b4c1-34443575cf4dn%40googlegroups.com.