我看到这个代码的几个实例在golang:在交换机中使用时,关键字类型的含义是什么?
func process(node ast.Node) Foo {
switch n := node.(type) {
// ... removed for brevity
}
}
ast.Node
是一个接口。是node.(type)
代码片段执行反射;找出接口的实际实现者?
我看到这个代码的几个实例在golang:在交换机中使用时,关键字类型的含义是什么?
func process(node ast.Node) Foo {
switch n := node.(type) {
// ... removed for brevity
}
}
ast.Node
是一个接口。是node.(type)
代码片段执行反射;找出接口的实际实现者?
是的。它被称为类型开关。它允许您根据您传递的接口的实际类型执行代码。
我认为the official documentation,以其例如,很清楚:
的开关也可以被用于发现的动态类型的接口 可变的。这种类型的开关在括号内使用类型断言的语法和 关键字类型。如果开关在表达式中声明了 变量,则该变量在每个子句中将具有相应的 类型。在这种情况下重用名称也是习惯用法,实际上在每种情况下声明一个具有相同名称的新变量,但不同类型的变量为 。
var t interface{}
t = functionOfSomeType()
switch t := t.(type) {
default:
fmt.Printf("unexpected type %T", t) // %T prints whatever type t has
case bool:
fmt.Printf("boolean %t\n", t) // t has type bool
case int:
fmt.Printf("integer %d\n", t) // t has type int
case *bool:
fmt.Printf("pointer to boolean %t\n", *t) // t has type *bool
case *int:
fmt.Printf("pointer to integer %d\n", *t) // t has type *int
}
你不应该使用的正确类型的程序过于频繁,但它的方便,当你需要它。使用示例:假设您实施数据库驱动程序,您可能必须根据Go变量的类型进行转换。这里的an extract of the go-sql/mysql driver:
// Scan implements the Scanner interface.
// The value type must be time.Time or string/[]byte (formatted time-string),
// otherwise Scan fails.
func (nt *NullTime) Scan(value interface{}) (err error) {
if value == nil {
nt.Time, nt.Valid = time.Time{}, false
return
}
switch v := value.(type) {
case time.Time:
nt.Time, nt.Valid = v, true
return
case []byte:
nt.Time, err = parseDateTime(string(v), time.UTC)
nt.Valid = (err == nil)
return
case string:
nt.Time, err = parseDateTime(v, time.UTC)
nt.Valid = (err == nil)
return
}
nt.Valid = false
return fmt.Errorf("Can't convert %T to time.Time", value)
}
它是TYPE SWITCH:
的开关也可以被用于发现的动态类型的接口 可变的。这种类型的开关在括号内使用类型断言的语法和 关键字类型。如果开关在表达式中声明了 变量,则该变量在每个子句中将具有相应的 类型。在这种情况下重用名称也是习惯用法,实际上在每种情况下声明一个具有相同名称的新变量,但不同类型的变量为 。
与一种类型的开关,就可以在一个接口值(只)的类型进行切换:
func do(v interface{}) string {
switch u := v.(type) {
case int:
return strconv.Itoa(u*2) // u has type int
case string:
mid := len(u)/2 // split - u has type string
return u[mid:] + u[:mid] // join
}
return "unknown"
}
do(21) == "42"
do("bitrab") == "rabbit"
do(3.142) == "unknown"