【问题标题】:Returning interfaces in Golang在 Golang 中返回接口
【发布时间】:2014-08-01 19:54:13
【问题描述】:

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

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 结构。

【问题讨论】:

  • 请说明您的实际问题是什么。理想情况下,您的帖子包含一个以问号结尾并提出具体问题的句子。我不太确定您的实际问题是什么。
  • @FUZxxl 他想从他的GetModel func 中返回实际的“结构”,但是那样不行,他必须使用类型断言,检查两个答案。

标签: struct interface go


【解决方案1】:

当返回类型为Model 时,您不能直接返回TrueFalseQuestions。它将始终隐式包装在 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 比起if else,我更喜欢用switch,看起来更简单,符合go风格
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2019-04-26
    • 2018-03-22
    • 1970-01-01
    • 2016-11-30
    • 2012-08-08
    • 2017-12-11
    • 2020-05-06
    • 2020-05-15
    • 1970-01-01
    相关资源
    最近更新 更多