在Golang中返回接口

时间:2014-08-01 19:54:14

标签: struct interface go

我正在尝试在结构上编写一个方法,该结构接受接口类型并返回该接口类型但转换为适当的类型。

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 {})
}

因此,当我使用GetModel()类型调用TrueFalseQuestions时,我想自动返回TrueFalseQuestions类型。我想这意味着我的GetModel()方法应该返回Model类型。这样,如果我传递MultiQuestion类型,则会返回MultiQuestion结构。

2 个答案:

答案 0 :(得分:4)

当返回类型为TrueFalseQuestions时,您无法直接返回Model。它将始终隐式包含在Model接口中。

要恢复TrueFalseQuestions,您需要使用类型断言。 (你还需要注意指针和值)

// this should be a pointer, because the interface methods all have pointer receivers
q := &TrueFalseQuestions{}
q = man.GetModel(&TrueFalseQuestions{}).(*TrueFalseQuestions)

如果你有一个MultiQuestions,那当然会感到恐慌,所以你应该检查ok值,或者使用类型开关

switch q := man.GetModel(&TrueFalseQuestions{}).(type) {
case *TrueFalseQuestions:
    // q isTrueFalseQuestions
case *MultiQuestions:
    // q is MultiQuestions
default:
    // unexpected type
}

答案 1 :(得分:1)

但是,您不能对返回的值使用类型断言。

func main() {
    var man Manager

    tfq := &TrueFalseQuestions{}
    q := man.GetModel(tfq)
    if v, ok := q.(*TrueFalseQuestions); ok {
        fmt.Println("v is true/false", v)
    } else if v, ok := q.(*MultiQuestions); ok {
        fmt.Println("v is mq", v)
    } else {
        fmt.Println("unknown", q)
    }

}

playground

相关问题