Skip to content

Instantly share code, notes, and snippets.

@KEINOS
Created June 25, 2023 01:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KEINOS/8a4dd77b034d6015af0acd0ba829836d to your computer and use it in GitHub Desktop.
Save KEINOS/8a4dd77b034d6015af0acd0ba829836d to your computer and use it in GitHub Desktop.
[Golang] Generics example function for string and slice of strings as an argument.

Generic Go Function: Handling Strictly Different Argument Types

Simple example of a Go function that uses generics and takes a string or slice of strings as arguments.

foo("Hello, world")
foo([]string{"Hello, world", "こんにちは、世界"})
package main

import "fmt"

func main() {
	foo("Hello, world")
	foo([]string{"Hello, world", "こんにちは、世界"})
}

func foo[T string | []string](input T) {
	switch values := any(input).(type) {
	case []string:
		for _, value := range values {
			fmt.Println(value)
		}
	default:
		fmt.Println(values)
	}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment