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)
}
}
- View it online @ GoPlayground