.(type) 在 go 中如何工作
How does .(type) work in go
func test(value interface{}) {
if res, ok := value.(string); ok {
fmt.Println(res)
}
}
如何去确认值的类型?
我没有发现 struct 中有任何东西可以表示类型。
请帮忙。
Under the covers, interfaces are implemented as two elements, a type and a value. The value, called the interface's dynamic value, is an arbitrary concrete value and the type is that of the value. For the int value 3, an interface value contains, schematically, (int, 3).
例如:
s:="123"
test(s)
你可以把 value
想成 (string, "123")
。
所以当你做 res, ok:=value.(string)
时,它可以找出 res
和 ok
.
func test(value interface{}) {
if res, ok := value.(string); ok {
fmt.Println(res)
}
}
如何去确认值的类型? 我没有发现 struct 中有任何东西可以表示类型。 请帮忙。
Under the covers, interfaces are implemented as two elements, a type and a value. The value, called the interface's dynamic value, is an arbitrary concrete value and the type is that of the value. For the int value 3, an interface value contains, schematically, (int, 3).
例如:
s:="123"
test(s)
你可以把 value
想成 (string, "123")
。
所以当你做 res, ok:=value.(string)
时,它可以找出 res
和 ok
.