Skip to content

Instantly share code, notes, and snippets.

@hassaku63
Last active November 6, 2022 13:57
Show Gist options
  • Save hassaku63/46ccb52948f4975e3734f81b22d9c5df to your computer and use it in GitHub Desktop.
Save hassaku63/46ccb52948f4975e3734f81b22d9c5df to your computer and use it in GitHub Desktop.
Type switch
package main
import (
"fmt"
"time"
)
func main() {
typeSwitch := func(v interface{}) {
switch v.(type) {
case string:
fmt.Printf("v, %v is string\n", v)
case int:
fmt.Printf("v, %v is int\n", v)
case float64:
fmt.Printf("v, %v is float64\n", v)
case time.Duration:
fmt.Printf("v, %v is time.Duraiton\n", v)
default:
fmt.Println("v is unrecognized")
}
}
typeSwitch(1)
typeSwitch(1.1)
typeSwitch("text")
typeSwitch(time.Second * 1)
typeSwitch(time.Now())
// $ go run .
// v, 1 is int
// v, 1.1 is float64
// v, text is string
// v, 1s is time.Duraiton
// v is unrecognized
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment