//example for interface
package main
import (
"fmt"
"sort"
)
type Interface interface {
Len() int
Less(i, j int) bool
Swap(i, j int)
}
//接口嵌套, 接口类型的嵌入不能嵌入本身
//当前接口声明的方法不能和嵌入其中接口类型的方法重名
type Sortable interface {
sort.Interface
Sort()
}
type SortableStrings [3]string //数组类型别名
//值表示法,一个接口类型的变量可以被赋予任何实现了这个接口类型的值
func (s SortableStrings) Len() int {
return len(s)
}
func (s SortableStrings) Less(i, j int) bool {
return s[i] < s[j]
}
func (s SortableStrings) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s SortableStrings) Sort() {
sort.Sort(s)
}
func main() {
_, ok := interface{}(SortableStrings{}).(sort.Interface) //类型断言表达式
if ok {
fmt.Printf("SortableStrings is interface of sort.Interface\n")
}
_, ok1 := interface{}(SortableStrings{}).(Sortable) //类型断言表达式
if ok1 {
fmt.Printf("SortableStrings is interface of Sortable\n")
}
ss := SortableStrings{"1", "3", "2"}
ss.Sort()
fmt.Println(ss)
//这里我们可以看到值方法中是无法改变源值(具体原因可以参考golang 指针学习部分)
}
从上面我们可以看到不能改变源值的顺序,那么怎样才能实现源值排序呢?我们可以用指针的方法
//指针引用
func (s *SortableStrings) Len() int {
return len(s)
}
func (s *SortableStrings) Less(i, j int) bool {
return s[i] < s[j]
}
func (s *SortableStrings) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s *SortableStrings) Sort() {
sort.Sort(s)
}
func main() {
//这里断言,需要改成指针类型
_, ok := interface{}(&SortableStrings{}).(sort.Interface) //类型断言表达式
if ok {
fmt.Printf("SortableStrings is interface of sort.Interface\n")
}
_, ok1 := interface{}(&SortableStrings{}).(Sortable) //类型断言表达式
if ok1 {
fmt.Printf("SortableStrings is interface of Sortable\n")
}
ss := SortableStrings{"1", "3", "2"}
ss.Sort()
fmt.Println(ss)
}
指针的方法排序源值,但是我们发现 SortableStrings 类型已经不再是 sort.Interface 接口类型的实现了。我们对SortableStrings类型稍作改变
//切片类型,引用类型别名
type SortableStrings []string
func (s SortableStrings) Len() int {
return len(s)
}
func (s SortableStrings) Less(i, j int) bool {
return s[i] < s[j]
}
func (s SortableStrings) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s SortableStrings) Sort() {
sort.Sort(s)
}
对引用类型的别名类型来说,值方法对接收者值得改变也会反应在其源值上。