首页 > 解决方案 > 通过嵌入类型返回接口

问题描述

我需要返回一个接口。但我收到一个错误:

cannot use B literal (type B) as type K in return argument:
    B does not implement K (missing Check method)

我想当我嵌入类型时,我得到了所有内部类型和接口类型的方法

package main

import (
    "fmt"
)

type K interface {
    Check()
}

type A struct {
    A string
}

type B struct {
    B A
}

func (a A) Check() {
    fmt.Println(a.A)
}

func newB(a A) K {
    return B{B: a}
}

func main() {
    a := A{A: "A struct"}
    b := newB(a)

    b.Check()

}

如何解决这个问题呢?

标签: gostructinterface

解决方案


这不是嵌入:

type B struct {
    B A
}

有了以上内容,您有:

var b B
b.B.Check()

这是嵌入:

type B struct {
  A
}

有了以上内容,您有:

var b B
b.Check()

你还有:

b.A.Check()

推荐阅读