嵌入匿名接口的结构的含义? [英] Meaning of a struct with embedded anonymous interface?

查看:77
本文介绍了嵌入匿名接口的结构的含义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 类型接口接口{
Len()int
Less(i,j int)bool
Swap(i,j int)
}

...

type reverse struct {
Interface
}

什么意思匿名接口接口在结构反向

解决方式

通过这种方式,reverse可以实现 sort.Interface ,我们可以重写一个特定的方法
而不必定义所有其他的 p>

 类型reverse struct {
//此嵌入式接口允许反向使用
的方法//另一个接口实现。
接口

code


$ b

注意,在这里它交换了 (j,i)而不是(i,j),并且这是为struct 反向声明的唯一方法即使反向执行 sort.Interface

  // Less返回与嵌入式实现Less方法相反的结果。 
func(r reverse)Less(i,j int)bool {
return r.Interface.Less(j,i)
}

无论在此方法中传递哪个结构,我们都会将其转换为新的反向结构。

  //反向返回数据的反向顺序。 
func反向(数据接口)接口{
return& reverse {data}
}

如果您认为如果这种方法不可行,您需要做什么才能获得真正的价值。


  1. 添加另一个 Reverse 方法添加到 sort.Interface

  2. 创建另一个ReverseInterface?

  3. ...

任何此更改都需要许多更多的代码行跨越数千个想要使用标准反向功能的软件包。


sort package:

type Interface interface {
    Len() int
    Less(i, j int) bool
    Swap(i, j int)
}

...

type reverse struct {
    Interface
}

What is the meaning of anonymous interface Interface in struct reverse?

解决方案

In this way reverse implements the sort.Interface and we can override a specific method without having to define all the others

type reverse struct {
        // This embedded Interface permits Reverse to use the methods of
        // another Interface implementation.
        Interface
}

Notice how here it swaps (j,i) instead of (i,j) and also this is the only method declared for the struct reverse even if reverse implement sort.Interface

// Less returns the opposite of the embedded implementation's Less method.
func (r reverse) Less(i, j int) bool {
        return r.Interface.Less(j, i)
}

Whatever struct is passed inside this method we convert it to a new reverse struct.

// Reverse returns the reverse order for data.
func Reverse(data Interface) Interface {
        return &reverse{data}
}

The real value comes if you think what would you have to do if this approach was not possible.

  1. Add another Reverse method to the sort.Interface ?
  2. Create another ReverseInterface ?
  3. ... ?

Any of this change would require many many more lines of code across thousands of packages that want to use the standard reverse functionality.

这篇关于嵌入匿名接口的结构的含义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆