回答

收藏

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

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

sort 包裹:% u  L$ A- x2 p% x
    type Interface interface    Len() int    Less(i,j int) bool    Swap(i,j int)}...type reverse struct    Interface}7 U, ?# N# N* {6 ^
Interfacestruct匿名界面的含义是什么?reverse?
, W# k* [  j- P1 x# h                                                               
9 \; `  l' ]9 @4 z0 ?/ _) D    解决方案:                                                                ) P+ s/ x+ E8 |" M; f
                                                                这样,反向实现sort.Interface,我们可以覆盖特定的方法而不必定义所有其他方法
/ N- k3 k4 r7 j# H, T
    type reverse struct        This embedded Interface permits Reverse to use the methods of     another Interface implementation.        Interface}
    0 m; {1 n5 T( P
注意如何在这里交换(j,i)而不是,即使实现了,(i,j)这也是声明结构的唯一方法reverse``reverse``sort.Interface
2 H+ `9 N% a8 ^' B- }6 o
    // 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)}
    " C& n0 G' Z2 `$ N, U* c
无论在这种方法中传递什么结构,我们都将其转化为新的reverse结构。
8 f7 ^  ?  _5 \9 g2 k: \! y
    // Reverse returns the reverse order for data.func Reverse(data Interface) Interface              return &reverse{data}}5 I3 ^, M  B$ _; K8 R
如果你认为这种方法不可行,你必须做什么,那么真正的价值就来了。
) ?1 W. _$ U1 K& X( x7 Q[ol]将另一个Reverse方法添加到sort.Interface?
; f5 ?0 Z  C6 f5 ?/ _0 F创建另一个反向接口?0 V/ h, {9 b1 h% r( m7 ]+ t4 ~; L
……?[/ol]任何这种变化都需要跨越成千上万的行代码来使用标准反向功能。
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则