Last active
November 6, 2022 13:57
-
-
Save hassaku63/46ccb52948f4975e3734f81b22d9c5df to your computer and use it in GitHub Desktop.
Type switch
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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