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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?