假设我有一些函数返回两种类型之一:键入A
和键入B
像这样:
func MyFunc(v bool) (interface{}) {
if v {
return &A{}
} else {
return &B{}
}
}
这里,根据某些逻辑(在这种情况下为v
的值),我想返回其他类型。如果要返回指针,将MyFunc
的返回值设置为空接口interface{}
是否正确?因为通常,该函数看起来像func MyFunc(v bool) (*T)
。但是,我想返回*A
或*B
,所以T
是未知的。做这个的最好方式是什么?我已经看过类型断言,但是我认为那不是我真正需要的。我还查看了帖子(cannot use type interface {} as type person in assignment: need type assertion),尽管它与此相关,但它所提出的问题与我在此处提出的问题不同。
更多信息:我写这篇文章是因为出现错误cannot use *T as type interface {} in return argument
。
只需返回interface{}
,就可以。
package main
import (
"fmt"
)
type A struct{}
type B struct{}
func MyFunc(v bool) (interface{}) {
if v {
return &A{}
} else {
return &B{}
}
}
func main() {
result := MyFunc(false)
switch result.(type) {
case *A:
fmt.Println("A.")
break
case *B:
fmt.Println("B.")
break
}
}