知识卡片
隐式接口复用排序实现
Go 按方法集判断类型是否满足接口。将 []Block 转为具名切片 sortable,由其三个排序方法支持使用 sort.Sort。var _ sort.Interface = sortable{} 会在构建期验证契约。
结构图:
classDiagram
class SortInterface[sort.Interface] {
<<interface>>
Len() int
Less(i int, j int) bool
Swap(i int, j int)
}
class sortable {
Len() int
Less(i int, j int) bool
Swap(i int, j int)
}
class Block
sortable ..|> SortInterface : 隐式实现
sortable o-- Block : 切片元素
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- 高效 Go 入门 2.2.4 オブジェクト指向プログラミング · 查看原书依据
sort.Interface のすべてのメソッドを実装する必要があります。
参考来源
- 位置:《効率的なGo》第 02 章 · 高效 Go 入门(来源项目 book-source,源文件 extracted/効率的なGo/_epub-src/OEBPS/ch02.xhtml#id86,2.2.4 オブジェクト指向プログラミング)
- 结论依据:清单 2-12 和 2-13 定义真实方法与编译时检查语句。
- 原始内容:sort.Interface のすべてのメソッドを実装する必要があります。