On Tuesday, 6 December 2022 at 21:05:48 UTC dple...@google.com wrote: > I am trying to figure out if there's a good way to build a helper that can > be used against different sets of nested types that have a common structure. > > So, for example, say there are two libraries, `lib1` and `lib2` and both > define types Foo, Bar, and Baz with: > > type Foo struct { ... } > type Bar struct { ... } > func (b *Bar) GetFoo() *Foo { ... } > type Baz struct { ... } > func (b *Baz) GetBar() *Bar { ... } > > But `lib1` and `lib2` both define different additional methods on some of > these structs, so I can't just merge them into a single library. >
It seems to me that lib1.{Foo,Bar,Baz} and lib2.{Foo,Bar,Baz} are completely different types. They just happen to have similar names. Hence I ask, what's the commonality that you're trying to expose? If it's that both lib1.Baz and lib2.Baz have a GetBar() method, then that sounds like an interface - except if one returns a lib1.Bar and the other returns a lib2.Bar, then they are not the same interface at all, so you're back to "these are completely different types". Is there something common in Foo ? > > I would like to write a helper function `HelperFn(baz ??)` such that I can > call `HelperFn(&lib1.Baz{})` and also `Helperfn(&lib2.Baz{})`. > > Why not just have HelperFn1(lib1.Baz) and HelperFn2(lib2.Baz)? Perhaps there is some point in your code where a variable could hold either a lib1.Baz or a lib2.Baz. If so, what's the type of that variable? And what's the helper function going to do with the value that you're passing in, which could be of either type? Whilst you can use generics in the way you've shown to call GetBar() and GetFoo(), you can't use generics for accessing struct members, so everything would have to be done via methods - even reading or setting elements of {lib1|lib2}.Foo. I think at the bottom there has to be *some* common interface. How important is static type checking in this application? You could always just write HelperFn(interface {}) which does type assertions on its parameter. Admittedly this is ugly: https://go.dev/play/p/14vs2Ce7P42 -- 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/cb23ef8d-5db9-4a02-b5dd-96576640b364n%40googlegroups.com.