Using go generics with GoLand and gotip
The addition of generics to go has been a contentious one, but it seems that it is going to finally be released in 1.18. I’ve seen discussions about this for a long time and remember a discussion with a friend in 2019 when I introduced him to go he said that he liked the language but didn’t understand why there were no generics. I have missed generics in some instances and even if generate can sometimes make for it, the space was still there.
So I’ve started to read about go’s implementation and decided to try it. The go2go tool that comes with go 1.17 is abandoned and lacks some functionalities of the spec, so I have to go with gotip. Installing is really simple, but then I wanted to make it work with Goland.
To get it to work I used the Run Code in GoLand from the
jetbrains tutorial but changed the GOROOT path to ~/sdk/gotip/
without needing any tool arguments.
GoLand (version 2021.2) only implements the draft version of the Type parameters design, so there are some errors that are incorrectly pointed, but the following program works like a charm:
package main
import "fmt"
type intOrString interface {
int | string
}
func test[T intOrString](x T) T {
return x
}
func main() {
fmt.Println(test("a"))
fmt.Println(test(2))
}
By the way, this shows one of the things that has started to bug me with go’s generics, the fact that we now have two types of interfaces that can only be used in certain contexts.