GoLand 2023.2 Help

How to use type parameters for generic programming

By using type parameters, you can write functions that handle incoming parameters without depending on the type specified in the function declaration.

For example, the PrintSliceInts function receives a slice of integers and prints it.

func PrintSliceInts(i []int) { for _, v := range i{ print(v) } } func main() { PrintSliceInts([]int {1,2,3,4,5,6,7,8,9}) }

To apply the same functionality to a slice of strings, you need to copy and paste the code of PrintSliceInts and make a new function called PrintSliceStrings, where everything is the same except for the signature.

You can rewrite the function and reuse your code. All you need is to introduce the type parameter and change the function parameter in the signature.

func PrintSlice[T any](s []T) { for _, v := range s{ print(v) } } func main() { PrintSlice([]int{1,2,3,4,5,6,7,8,9}) PrintSlice([]string {"a","b","c","d"}) }

Run code in GoLand

Ensure that you installed and use Go 1.18 beta 1 or later. You can check your current Go version by opening settings and navigating to Go | GOROOT. To open settings, press Control+Alt+S.

Also, check that the go.mod file (if you use Go modules) references Go 1.18 beta 1 or later.

Check the Go version in settings
  • Click the Run Application icon (the Run Application icon in the gutter) in the gutter and select Run 'go build project_name'. Alternatively, press Control+Shift+F10.

Run code in the go.dev playground

You can open go.dev/play and run your code here. Note that before running you need to select Go dev branch.

Alternatively, use the Share in Playground action in GoLand.

  1. In the editor, press Control+Shift+A to search for actions.

  2. Type Share in Playground and press Enter. Alternatively, use the following shortcut in the editor: Command Alt Shift S.

  3. At go.dev, select Go dev branch, and click the Run button.

Last modified: 12 December 2022