struct - 在 Golang 中返回接口(interface)

标签 struct interface go

我正在尝试在接受接口(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/

相关文章:

C 编程 - 结构体中的整数值在赋值后变为 "random"

c - 无法在 C 中传递结构指针以创建顺序列表

java - OutputStream 作为接口(interface)

sql - sqlmock:期望值不匹配(完全相同的查询)

c - 访问嵌套结构成员的多种方式

types - golang 在 switch 中动态创建接收器

java - 扩展/继承Java中的2个类

json - 在 Go 中处理调试错误

vba - 如何在不寻常的时间格式golang之间进行转换

arrays - 带有数组指针的结构体在 print_stack() 函数中打印 "random numbers"