代码拉取完成,页面将自动刷新
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()
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。