Struct 返回Golang中的接口

Struct 返回Golang中的接口,struct,interface,go,Struct,Interface,Go,我试图在结构上编写一个方法,该方法接受接口类型并返回该接口类型,但转换为适当的类型 type Model interface { GetEntity() } type TrueFalseQuestions struct { //some stuff } func (q *TrueFalseQuestions) GetEntity() { //some stuff } type MultiQuestions struct { //some stuff } fun

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

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

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

当返回类型为
Model
时,不能直接返回
TrueFalseQuestions
。它总是隐式地包装在
模型
接口中

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

如果遇到
多问题
,这当然会导致恐慌,因此您应该检查
ok
值,或者使用类型开关

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

当返回类型为
Model
时,不能直接返回
TrueFalseQuestions
。它总是隐式地包装在
模型
接口中

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

如果遇到
多问题
,这当然会导致恐慌,因此您应该检查
ok
值,或者使用类型开关

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

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

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

}

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

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

}

请说明您的实际问题是什么。理想情况下,您的帖子包含一个以问号结尾的句子,并提出一个具体问题。我不太确定你的实际问题是什么。@Fuzzxl他想从他的
GetModel
func返回实际的“struct”,但这样不行,他必须使用类型断言,检查两个答案。请说明你的实际问题是什么。理想情况下,您的帖子包含一个以问号结尾的句子,并提出一个具体问题。我不太确定你的实际问题是什么。@fuzzxl他想从他的
GetModel
func返回实际的“struct”,但它不能那样工作,他必须使用类型断言,检查两个答案。+1我更喜欢使用开关而不是if-else,看起来更简单,符合围棋风格+1我更喜欢使用这个开关,而不是if-else,看起来更简单,符合围棋风格