GO接口

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) 
	}
}
相關文章
相關標籤/搜索