为什么第一个示例失败,但第二个成功?
做这种断言的正确方法是什么?
示例 1 https://play.golang.org/p/4LRGQLdGPB
// example 1
type Packet map[string]interface{}
func get(pack interface{}) {
if packet, ok := pack.(Packet); !ok {
fmt.Printf("error: %#v, %#v\n", pack, packet)
}
}
func main() {
pack := make(map[string]interface{})
pack["qwe"] = 123
get(pack)
}
// error: map[string]interface {}{"qwe":123}, main.Packet(nil)
示例 2 https://play.golang.org/p/Pd9jvvNrq5
// example 2
type Packet map[string]interface{}
func get(pack interface{}) {
var p Packet
if packet, ok := pack.(map[string]interface{}); !ok {
fmt.Printf("%#v, %#v\n", pack, packet)
} else {
p = packet
}
fmt.Printf("%#v\n", p)
}
func main() {
pack := make(map[string]interface{})
pack["qwe"] = 123
get(pack)
}
// main.Packet{"qwe":123}
慕仙森
至尊宝的传说
相关分类