-
Notifications
You must be signed in to change notification settings - Fork 36
type switch #9
Comments
This is a good idea. We almost already have a way to do this right now. Consider this Playground example: package main
import "fmt"
func printType[T] (x T) {
switch x := x.(type) {
case int:
fmt.Printf("int(%d)", x)
case string:
fmt.Printf("string(%s)", x)
}
}
func main() {
printType[int](42)
printType[string]("hello")
} Parsing and type-checking works fine. Type parameters are internally considered to have underlying type func printType__int (x int) {
switch x := x.(type) {
case int:
fmt.Printf("int(%d)", x)
case string:
fmt.Printf("string(%s)", x)
}
} In Go, you can't use a type switch on non-interface types like func printType__int (x int) {
fmt.Printf("int(%d)", x)
}
func printType_string(x string) {
fmt.Printf("string(%s)", x)
} |
You could also cast the parameter to an interface {} switch x := (interface {})(x).(type) If that was easier - the go compiler will then prune the switch for you. |
Can one type switch within the implementation of a generic function? something like this might be reasonable:
The text was updated successfully, but these errors were encountered: