5 ms·
Here's the way you can solve the first problem with generics in go, almost exactly as he described: https://go.dev/play/p/GrLYBj3N0jr https://go.dev/play/p/GrL
by swid 4y ago
Here's the way you can solve the first problem with generics in go, almost exactly as he described:
https://go.dev/play/p/GrLYBj3N0jr https://go.dev/play/p/GrLYBj3N0jr
The trick is to define the fish tank like so:
type fishTank struct {
container[fish]
}
- timbray 4y agoThanks, yep, that works. Updated the blog piece and will improve the Quamina code a bit too.
- masklinn 4y agoFWIW the original works as well, but because you're using a typedef (not an alias) you have to convert from your own type to the underlying: func (t *fishTank) fishCount() string { return fmt.Sprintf("How many fishies? %d!", (*container[fish])(t).size()) } that's because type fishTank container[fish] creates a completely new and independent type with container[fish] as the underlying implementation. An alternative is to just alias: type fishTank = container[fish] however in that case you can't define methods on fishTank, because it's literally just a shorthand for container[fish].
- timbray 4y agoOK, that `(*container[fish])(t).size())` idiom is um non-obvious. Somebody needs to write a nice simple bloggy step-by-step walk through all these gyrations.
- masklinn 4y agoIt's not really an idiom. The normal conversion expression is T(v) but that doesn't work if T is a pointer type, because it's parsed as *(T(v)) so the types don't match. So you need (*T)(v) to ensure the type part includes the pointer specifier.