我试图用以下代码理解接口嵌入.
我有以下内容:
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
}
Run Code Online (Sandbox Code Playgroud)
现在,如果我有以下内容:
func returninterface() MyprojectV1alpha1Interface {
//does something and returns me MyprojectV1alpha1Interface
}
temp := returninterface()
Run Code Online (Sandbox Code Playgroud)
现在,从MyprojectV1alpha1Interface如果我想调用
创建SampleInterface的功能
我需要做什么?
另外,请解释一下这个界面在Golang中是如何工作的.
在这个定义中:
type MyprojectV1alpha1Interface interface {
RESTClient() rest.Interface
SamplesGetter
}
Run Code Online (Sandbox Code Playgroud)
你MyprojectV1alpha1Interface嵌入了SamplesGetter界面.
在另一个接口中嵌入接口意味着SamplesGetter可以通过嵌入接口(MyprojectV1alpha1Interface)调用嵌入式接口()的所有方法.
这意味着您可以SamplesGetter在任何实现的对象上调用任何方法MyprojectV1alpha1Interface.
因此,一旦你MyprojectV1alpha1Interface在temp变量中得到一个对象,就可以调用该Samples方法(使用合适的namespace,我无法从您发布的代码中猜出):
sampleInt := temp.Samples("namespace here")
Run Code Online (Sandbox Code Playgroud)
sampleInt然后会有一个SampleInterface对象,因此您可以Create使用您的sampleInt变量调用该函数:
sample, err := sampleInt.Create(<you should use a *v1alpha1.Sample here>)
Run Code Online (Sandbox Code Playgroud)
有关接口如何工作的更多详细信息,我建议您转到官方规范和示例:
https://golang.org/ref/spec#Interface_types
https://gobyexample.com/interfaces