lf2*_*215 21 struct pointers interface go
如果我有:
type foo struct{
}
func bar(baz interface{}) {
}
Run Code Online (Sandbox Code Playgroud)
以上是一成不变的 - 我无法改变foo或bar.另外,baz必须转换回bar内的foo结构指针.如何将&foo {}转换为接口{},以便在调用bar时将其用作参数?
ANi*_*sus 48
要打开*foo到一个interface{}很简单:
f := &foo{}
bar(f) // every type implements interface{}. Nothing special required
Run Code Online (Sandbox Code Playgroud)
为了回到a *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
}
Run Code Online (Sandbox Code Playgroud)
或类型开关(类似,但如果baz可以是多种类型,则很有用):
func bar(baz interface{}) {
switch f := baz.(type) {
case *foo: // f is of type *foo
default: // f is some other type
}
}
Run Code Online (Sandbox Code Playgroud)
小智 6
使用反射
reflect.ValueOf(myStruct).Interface().(newType)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
43925 次 |
| 最近记录: |