package main import ( "fmt" "sort" "math/rand" ) //接口不能包含变量,不能有方法的实现 type Usb interface{ Start() Stop() } //Phone实现Usb接口 type Phone struct{ } func (p Phone) Start() { fmt.Println("手机开始工做") } func (p Phone) Stop() { fmt.Println("手机中止工做") } //相机实现Usb接口 type Camera struct{ } func (c Camera) Start() { fmt.Println("相机开始工做") } func (c Camera) Stop() { fmt.Println("相机中止工做") } type Computer struct{ } func (c Computer) Working(usb Usb) { usb.Start() usb.Stop() } type Usb2 interface { Usb //接口继承,要实现Usb2必须也要实现Usb的方法 test() } type Student struct{ Name string Age int Score float64 } type StudentSlice []Student //实现Interface接口 func(sl StudentSlice) Len() int { return len(sl) } func (sl StudentSlice) Less(i int, j int) bool { return sl[i].Score < sl[j].Score } func (sl StudentSlice) Swap(i int, j int) { //temp := sl[i] //sl[i] = sl[j] //sl[j] = temp //上面三行能够简写 sl[i],sl[j] = sl[j],sl[i] } func main() { cp := Computer{} ca := Camera{} ph := Phone{} cp.Working(ca) cp.Working(ph) var usb Usb //usb.Start() //这样是不容许的 usb = ca usb.Start();//这就能够 var sl StudentSlice for i := 0; i < 10; i++ { stu := Student{ Name: fmt.Sprintf("test|%d", rand.Intn(100)), Age: rand.Intn(100), Score: rand.Float64() * 100, } sl = append(sl, stu) } for _,v := range(sl) { fmt.Println(v) } fmt.Println("-------------------------") sort.Sort(sl) //排序后 for _,v := range(sl) { fmt.Println(v) } }