Skip to content

Instantly share code, notes, and snippets.

@jahentao
Created March 24, 2019 13:15
Show Gist options
  • Save jahentao/ebb7801a8ca469bb20011c4dbf2369bf to your computer and use it in GitHub Desktop.
Save jahentao/ebb7801a8ca469bb20011c4dbf2369bf to your computer and use it in GitHub Desktop.
Go语言语法片段
// 判断go语言中变量的类型
package main
import (
"fmt"
)
var container = []string{"zero", "one", "two"}
func main() {
container := map[int]string{0: "zero", 1: "one", 2: "two"}
// 方式1。
_, ok1 := interface{}(container).([]string)
_, ok2 := interface{}(container).(map[int]string)
if !(ok1 || ok2) {
fmt.Printf("Error: unsupported container type: %T\n", container)
return
}
fmt.Printf("The element is %q. (container type: %T)\n",
container[1], container)
// 方式2。
elem, err := getElement(container)
if err != nil {
fmt.Printf("Error: %s\n", err)
return
}
fmt.Printf("The element is %q. (container type: %T)\n",
elem, container)
}
func getElement(containerI interface{}) (elem string, err error) {
switch t := containerI.(type) {
case []string:
elem = t[1]
case map[int]string:
elem = t[1]
default:
err = fmt.Errorf("unsupported container type: %T", containerI)
return
}
return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment