package mainimport "fmt"func weirdFunc(i int) interface{}{ if i == return "zero" } return i}func main() var i = 5 var w = weirdFunc(5) / this example works! if tmp,ok := w.(int); ok i = tmp } fmt.Println("i =",i)}; d. z3 ^/ d$ y7 b( X% q
你知道如何使用 Go 介绍得很好interface{}吗?! Y' |; h; V9 W1 b1 ^$ Y: B1 G
具体问题:6 {9 B7 J/ R+ N5 J 如何获得 w 真实类型?# V. n& q* ~: T# [) f" {( U1 E
有没有办法获得字符串的类型? % E- x2 W( L: Q! J) h, p有没有办法用类型的字符串来表示转换值? $ g( y( V" e: p3 g# ~解决方案: 4 {9 k5 F* ^% C/ o6 W 也可以做类型切换: & k0 g7 _+ i- R4 Y4 y
switch v := myInterface.(type) {case int: // v is an int here,so e.g. v 1 is possible. fmt.Printf("Integer: %v",v)case float64: // v is a float64 here,so e.g. v 1.0 is possible. fmt.Printf("Float64: %v",v)case string: // v is a string here,so e.g. v " Yeah!" is possible. fmt.Printf("String: %v",v)default: // And here I'm feeling dumb. ) fmt.Printf("I don't know,ask stackoverflow.")} 2 y# e3 Z, z3 D) j