1.基本使用 接口是引用类型
package main
import "fmt"
type Usb interface {
Start(a int) int
Stop()
}
type Phone struct {
}
type Camera struct {
}
type Computer struct {
}
func (p Phone) Start(a int) int {
fmt.Printf("1.Phone Start 方法:%v\n", a)
return a + 1
}
func (p Phone) Stop() {
fmt.Printf("2.Phone Stop 方法\n")
}
func (c Camera) Start(a int) int {
fmt.Printf("1.Camera Start 方法:%v\n", a)
return a + 1
}
func (c Camera) Stop() {
fmt.Printf("2.Camera Stop 方法\n")
}
func (c Computer) Working(usb Usb, a int) (res int) {
res = usb.Start(a)
usb.Stop()
return res
}
func main() {
p := Phone{}
ca := Camera{}
c1 := Computer{}
res := c1.Working(p, 20)
fmt.Printf("3. Working返回数据%v\n", res)
res2 := c1.Working(ca, 50)
fmt.Printf("4. Working返回数据%v\n", res2)
var p2 Phone
var a Usb = p2
a.Start(88)
a.Stop()
}
输出
1.Phone Start 方法:20
2.Phone Stop 方法
3. Working返回数据21
1.Camera Start 方法:50
2.Camera Stop 方法
4. Working返回数据51
1.Phone Start 方法:88
2.Phone Stop 方法
2 最佳实践
package main
import (
"fmt"
"math/rand"
"sort"
)
type Student struct {
Name string
Age int
Score float64
}
type StudentSlice []Student
func (stu StudentSlice) Len() int {
return len(stu)
}
func (stu StudentSlice) Less(i, j int) bool {
return stu[i].Score < stu[j].Score
}
func (stu StudentSlice) Swap(i, j int) {
stu[i], stu[j] = stu[j], stu[i]
}
func main() {
var studentSlice StudentSlice
for i := 0; i < 10; i++ {
stu := Student{
Name: fmt.Sprintf("名字%d", rand.Intn(100)),
Age : rand.Intn(100),
Score: float64(rand.Intn(100)),
}
studentSlice = append(studentSlice, stu)
}
fmt.Printf("--------学生信息--------\n")
for index, stu := range studentSlice{
fmt.Printf("%v.Name:%v\n", index, stu.Name)
fmt.Printf("%v.Age:%v\n", index, stu.Age)
fmt.Printf("%v.Score:%v\n\n", index, stu.Score)
}
fmt.Printf("--------根据分数排序后学生信息--------\n")
sort.Sort(studentSlice)
for index, stu := range studentSlice {
fmt.Printf("%v.Name:%v\n", index, stu.Name)
fmt.Printf("%v.Age:%v\n", index, stu.Age)
fmt.Printf("%v.Score:%v\n\n", index, stu.Score)
}
}
输出
--------学生信息--------
0.Name:名字81
0.Age:87
0.Score:47
1.Name:名字59
1.Age:81
1.Score:18
2.Name:名字25
2.Age:40
2.Score:56
3.Name:名字0
3.Age:94
3.Score:11
4.Name:名字62
4.Age:89
4.Score:28
5.Name:名字74
5.Age:11
5.Score:45
6.Name:名字37
6.Age:6
6.Score:95
7.Name:名字66
7.Age:28
7.Score:58
8.Name:名字47
8.Age:47
8.Score:87
9.Name:名字88
9.Age:90
9.Score:15
--------根据分数排序后学生信息--------
0.Name:名字0
0.Age:94
0.Score:11
1.Name:名字88
1.Age:90
1.Score:15
2.Name:名字59
2.Age:81
2.Score:18
3.Name:名字62
3.Age:89
3.Score:28
4.Name:名字74
4.Age:11
4.Score:45
5.Name:名字81
5.Age:87
5.Score:47
6.Name:名字25
6.Age:40
6.Score:56
7.Name:名字66
7.Age:28
7.Score:58
8.Name:名字47
8.Age:47
8.Score:87
9.Name:名字37
9.Age:6
9.Score:95