Ai
1 Star 0 Fork 0

叶明志/golang练习

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
main.go 1.46 KB
一键复制 编辑 原始数据 按行查看 历史
yemingzhi 提交于 2020-03-29 20:03 +08:00 . 前面知识点的复习
package main
import (
"fmt"
"math/rand"
"sort"
)
type Student struct {
Name string
Age int
Id string
}
type StudentArray []Student
func (stu StudentArray) Len() int {
return len(stu)
}
func (stu StudentArray) Less(i, j int) bool {
return stu[i].Age > stu[j].Age
}
func (stu StudentArray) Swap(i, j int) {
stu[i], stu[j] = stu[j], stu[i]
}
//SortByInterface sort.Sort里面调用的是一个接口,只要结构实现了接口的方法Len、Less、Swap
//就可以使用
func SortByInterface() {
var stua StudentArray
for i := 0; i < 10; i++ {
var stu Student = Student{
Name: fmt.Sprintf("stu%d", rand.Intn(10)),
Age: rand.Intn(100),
Id: fmt.Sprintf("110%d", rand.Intn(100000)),
}
stua = append(stua, stu)
}
fmt.Println("Before Sort")
for _, val := range stua {
fmt.Println(val)
}
fmt.Println("After Sort")
sort.Sort(stua)
for _, val := range stua {
fmt.Println(val)
}
}
type Reader interface {
Read()
}
type Writer interface {
Write()
}
type ReadWrite interface { //接口的嵌套
Reader
Writer
}
type Lock interface {
Lock()
Unlock()
}
type File struct {
Name string
}
func (f *File) Write() {
fmt.Printf("My name is %s\n", f.Name)
}
func (f *File) Read() {
fmt.Printf("I am reading data\n")
}
func Test(rw ReadWrite) {
rw.Write()
rw.Read()
}
func Test1(rw ReadWrite) {
rw.Read()
rw.Write()
}
func testInterface() {
var f *File = &File{
Name: "golang",
}
Test1(f)
}
func main() {
// SortByInterface()
testInterface()
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/yemingzhi/GolangLearnPractice1.git
git@gitee.com:yemingzhi/GolangLearnPractice1.git
yemingzhi
GolangLearnPractice1
golang练习
2bf136849dce

搜索帮助