回答

收藏

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

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

sort 包裹:: c! \/ e  r/ e
    type Interface interface    Len() int    Less(i,j int) bool    Swap(i,j int)}...type reverse struct    Interface}0 b% \5 c, u" S
Interfacestruct匿名界面的含义是什么?reverse?
* t% J. e& @- j- O9 q0 O$ v: `                                                               
* E! X  C; V2 h- S  v: R    解决方案:                                                                ; `5 F' u0 V5 N4 Y7 I5 P
                                                                这样,反向实现sort.Interface,我们可以覆盖特定的方法而不必定义所有其他方法5 l8 W. t2 g6 T8 _; ?: l0 a* i6 j
    type reverse struct        This embedded Interface permits Reverse to use the methods of     another Interface implementation.        Interface}$ c3 G! G9 ^" D: e8 v" `
注意如何在这里交换(j,i)而不是,即使实现了,(i,j)这也是声明结构的唯一方法reverse``reverse``sort.Interface
* [! R0 U& Q- q6 Z5 }0 U! N
    // 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)}
    ' \" n- W- l# m7 ?8 h" x
无论在这种方法中传递什么结构,我们都将其转化为新的reverse结构。; P% T0 P. p  z& }" P+ d* p
    // Reverse returns the reverse order for data.func Reverse(data Interface) Interface              return &reverse{data}}
    % w- q5 \$ c( X0 ^: x
如果你认为这种方法不可行,你必须做什么,那么真正的价值就来了。
$ o+ |5 v0 _8 k& o; u[ol]将另一个Reverse方法添加到sort.Interface?- \* r3 L: |& E( h  M
创建另一个反向接口?9 _- e" I$ e; Y3 y5 P
……?[/ol]任何这种变化都需要跨越成千上万的行代码来使用标准反向功能。
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则