dphe5602 2014-08-01 19:54
浏览 96
已采纳

在Golang中返回接口

I am trying to write a method on a struct that takes in a interface type and returns that interface type but converted to the appropriate type.

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

So when I call GetModel() with type TrueFalseQuestions I want to automatically return a TrueFalseQuestions type. I figured that would mean that my GetModel() method should return a Model type. That way if I pass a MultiQuestion type a MultiQuestion struct is returned.

  • 写回答

2条回答 默认 最新

  • duanjianl183188 2014-08-01 20:04
    关注

    You can't directly return a TrueFalseQuestions when the return type is Model. It will always be implicitly wrapped in a Model interface.

    To get the TrueFalseQuestions back, you need to use a type-assertion. (you also need watch out for pointers vs values)

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

    That of course can panic if you got a MultiQuestions, so you should check the ok value, or use a type switch

    switch q := man.GetModel(&TrueFalseQuestions{}).(type) {
    case *TrueFalseQuestions:
        // q isTrueFalseQuestions
    case *MultiQuestions:
        // q is MultiQuestions
    default:
        // unexpected type
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器