【问题标题】:Understanding interface inside interface(Embedded Interface)了解接口内部的接口(嵌入式接口)
【发布时间】:2018-12-09 17:34:22
【问题描述】:

我试图用下面的代码理解接口嵌入。

我有以下几点:

type MyprojectV1alpha1Interface interface {
    RESTClient() rest.Interface
    SamplesGetter
}

// SamplesGetter has a method to return a SampleInterface.
// A group's client should implement this interface.
type SamplesGetter interface {
    Samples(namespace string) SampleInterface
}

// SampleInterface has methods to work with Sample resources.
type SampleInterface interface {
    Create(*v1alpha1.Sample) (*v1alpha1.Sample, error)
    Update(*v1alpha1.Sample) (*v1alpha1.Sample, error)
    Delete(name string, options *v1.DeleteOptions) error
    DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error
    Get(name string, options v1.GetOptions) (*v1alpha1.Sample, error)
    List(opts v1.ListOptions) (*v1alpha1.SampleList, error)
    Watch(opts v1.ListOptions) (watch.Interface, error)
    Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.Sample, err error)
    SampleExpansion
}

现在如果我有以下情况:

func returninterface() MyprojectV1alpha1Interface {
//does something and returns me MyprojectV1alpha1Interface
}
temp := returninterface()

现在,如果我想调用 MyprojectV1alpha1Interface

SampleInterface的创建函数

我需要做什么?

另外,请解释一下这个接口在 Golang 中是如何工作的。

【问题讨论】:

    标签: go go-interface


    【解决方案1】:

    在这个定义中:

    type MyprojectV1alpha1Interface interface {
        RESTClient() rest.Interface
        SamplesGetter
    }
    

    您的MyprojectV1alpha1Interface 嵌入了SamplesGetter 接口。

    将一个接口嵌入另一个接口意味着嵌入接口 (SamplesGetter) 的所有方法都可以通过嵌入接口 (MyprojectV1alpha1Interface) 调用。

    这意味着您可以在任何实现MyprojectV1alpha1Interface 的对象上调用任何SamplesGetter 方法。

    因此,一旦您在temp 变量中获得MyprojectV1alpha1Interface 对象,您就可以调用Samples 方法(使用合适的namespace,我无法从您发布的代码中猜到):

    sampleInt := temp.Samples("namespace here")
    

    sampleInt 将拥有一个SampleInterface 对象,因此您可以使用您的sampleInt 变量调用Create 函数:

    sample, err := sampleInt.Create(<you should use a *v1alpha1.Sample here>)
    

    有关接口如何工作的更多详细信息,我建议您查看官方规范和示例:

    https://golang.org/ref/spec#Interface_types

    https://gobyexample.com/interfaces

    【讨论】:

    • 很棒的解释,非常感谢。我对接口有所了解。但是,对接口嵌入感到困惑。但是,现在它一清二楚。谢谢
    • 这是很好的解释@eugenioy。但这是否意味着将接口嵌入另一个接口可能会带来风险?
    • 不确定你所说的风险是什么意思@jack_t,嵌入是一种在 Go 中简化组合的方法
    猜你喜欢
    • 1970-01-01
    • 2010-11-05
    • 1970-01-01
    • 1970-01-01
    • 2015-11-06
    • 2016-01-26
    • 2011-12-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多