回答

收藏

具有嵌入式匿名接口的结构的含义?

技术问答 技术问答 218 人阅读 | 0 人回复 | 2023-09-12

sort 包裹:& D0 q3 e2 }+ a5 l- t2 v
    type Interface interface    Len() int    Less(i,j int) bool    Swap(i,j int)}...type reverse struct    Interface}
    ( ~8 w6 Y; c$ D) h
Interfacestruct匿名界面的含义是什么?reverse?
: M; M, ^0 O3 `8 U6 V                                                               
4 ?4 h4 ?/ r5 p    解决方案:                                                               
, o# D6 w* ]) _: b1 v+ U; w                                                                这样,反向实现sort.Interface,我们可以覆盖特定的方法而不必定义所有其他方法6 M+ D' v. R* p2 K$ W; B$ g
    type reverse struct        This embedded Interface permits Reverse to use the methods of     another Interface implementation.        Interface}
    * p8 y  G; {$ a! Z, M6 F2 z
注意如何在这里交换(j,i)而不是,即使实现了,(i,j)这也是声明结构的唯一方法reverse``reverse``sort.Interface& P0 _- t" z/ `6 _
    // 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)}
    4 c: }5 N/ L: ~
无论在这种方法中传递什么结构,我们都将其转化为新的reverse结构。. ~8 L0 o0 m0 b" M( J
    // Reverse returns the reverse order for data.func Reverse(data Interface) Interface              return &reverse{data}}
    2 H# W5 A6 h2 U
如果你认为这种方法不可行,你必须做什么,那么真正的价值就来了。, j- [& _( S; p' }* \& G* B
[ol]将另一个Reverse方法添加到sort.Interface?- d; d( K/ q9 t
创建另一个反向接口?
- M8 j* \$ O, @3 P  z% |3 V……?[/ol]任何这种变化都需要跨越成千上万的行代码来使用标准反向功能。
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则