ANi*_*sus 48
*foointerface{}
f := &foo{}
bar(f) // every type implements interface{}. Nothing special required
*foo
func bar(baz interface{}) {
f, ok := baz.(*foo)
if !ok {
// baz was not of type *foo. The assertion failed
}
// f is of type *foo
}
baz
func bar(baz interface{}) {
switch f := baz.(type) {
case *foo: // f is of type *foo
default: // f is some other type
}
}
- @JuandeParras:如果你不知道`baz`可能是什么类型,那么你将不得不使用反射(`import'反映"`).这就像`encoding/json`这样的包可以在不事先知道的情况下基本上编码任何类型. (5认同)