4 ms·
Wow, what a horrid and cool way to create a function that accepts generic types in Go :-) func add(a interface{}, b interface{}) interface{} { if a,
by bjarneh 5y ago
Wow, what a horrid and cool way to create a function that accepts generic types in Go :-)
func add(a interface{}, b interface{}) interface{} {
if a, ok := a.(int); ok {
if b, ok := b.(int); ok {
return a + b
}
}
if a, ok := a.(string); ok {
if b, ok := b.(string); ok {
return a + b
}
}
panic("incompatible types")
}
- rob74 5y agoYou're a bit (~10 years) late to the game of complaining about having to use `interface{}` as a substitute for generics in Go (although it has worked pretty well in most cases). Go 1.18 will have "real" generics, so stuff like this can be expressed more elegantly...
- bjarneh 5y agoI've been writing Go since 2009, so I'm not late to the party. I was there when it started :-)
- Cthulhu_ 5y agobrouhaha go bad. Why are you writing an add function when 1 + 1 will do? I mean I know there's better examples out there, but in practice I've not missed a lack of generics in Go yet. Mind you, I'm not writing libraries for e.g. json parsing. Actually there is one place in my application where I use interface{}, it's a bit of code that converts values to XML strings, but it needs different logic for different types. I don't think generics will solve that: https://go.dev/play/p/TtwyNZ7oOPx https://go.dev/play/p/TtwyNZ7oOPx
- jatone 5y agoi think constraints will help which are part of generics at least you'll be able to limit the types your functions accept. but otherwise no, generics do not solve sum types by themselves.
- mseepgood 5y agohttps://go.dev/play/p/H5ImcpTyju0?v=gotip https://go.dev/play/p/H5ImcpTyju0?v=gotip