我正在尝试在接受接口(interface)类型并返回该接口(interface)类型但转换为适当类型的结构上编写一个方法。
type Model interface {
GetEntity()
}
type TrueFalseQuestions struct {
//some stuff
}
func (q *TrueFalseQuestions) GetEntity() {
//some stuff
}
type MultiQuestions struct {
//some stuff
}
func (q *MultiQuestions) GetEntity() {
//some stuff
}
type Manager struct {
}
func (man *Manager) GetModel(mod Model) Model {
mod.GetEntity()
return mod
}
func main() {
var man Manager
q := TrueFalseQuestions {}
q = man.GetModel(&TrueFalseQuestions {})
}
因此,当我使用 TrueFalseQuestions
类型调用 GetModel()
时,我想自动返回一个 TrueFalseQuestions
类型。我认为这意味着我的 GetModel()
方法应该返回一个 Model
类型。这样,如果我传递一个 MultiQuestion
类型,就会返回一个 MultiQuestion
结构。
最佳答案
当返回类型为 Model
时,您不能直接返回 TrueFalseQuestions
。它将始终隐式包装在 Model
接口(interface)中。
要返回 TrueFalseQuestions
,您需要使用类型断言。 (您还需要注意指针与值)
// this should be a pointer, because the interface methods all have pointer receivers
q := &TrueFalseQuestions{}
q = man.GetModel(&TrueFalseQuestions{}).(*TrueFalseQuestions)
如果你得到一个 MultiQuestions
,那当然会 panic,所以你应该检查 ok
值,或者使用类型开关
switch q := man.GetModel(&TrueFalseQuestions{}).(type) {
case *TrueFalseQuestions:
// q isTrueFalseQuestions
case *MultiQuestions:
// q is MultiQuestions
default:
// unexpected type
}
关于struct - 在 Golang 中返回接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25087726/