- 将现有练习及 module 文件迁移至 go/practice,保持代码和依赖不变 - 新增 go/projects 项目区说明,更新目录约定与开发命令 BREAKING CHANGE: Go 练习命令需改在 go/practice 目录下执行
110 lines
2.0 KiB
Go
110 lines
2.0 KiB
Go
package testing
|
|
|
|
import (
|
|
"fmt"
|
|
"sort"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
func TestNormal(t *testing.T) {
|
|
numbers := map[int][]int{
|
|
1: {8, 2, 4, 4},
|
|
2: {0, 5, 3},
|
|
3: {1},
|
|
}
|
|
for _, numbers := range numbers {
|
|
middle := GetMiddNumber(numbers)
|
|
t.Log(middle)
|
|
}
|
|
|
|
}
|
|
|
|
func GetMiddNumber(numbers []int) float64 {
|
|
sort.Ints(numbers)
|
|
length := len(numbers)
|
|
isOddNUmber := length%2 == 1
|
|
if !isOddNUmber {
|
|
return float64(numbers[length/2-1]+numbers[length/2]) / 2.0
|
|
}
|
|
return float64(numbers[length/2])
|
|
}
|
|
|
|
func TestChannel(t *testing.T) {
|
|
var ball = make(chan string)
|
|
kickBall := func(playerName string) {
|
|
for {
|
|
t.Log(<-ball, "传球", "\n")
|
|
time.Sleep(time.Second)
|
|
ball <- playerName
|
|
}
|
|
}
|
|
go kickBall("张三")
|
|
go kickBall("李四")
|
|
go kickBall("王二麻子")
|
|
go kickBall("刘大")
|
|
ball <- "裁判" // 开球
|
|
var c chan bool // 一个零值nil通道
|
|
<-c // 永久阻塞在此
|
|
}
|
|
|
|
func TestFeature1(t *testing.T) {
|
|
type Person struct {
|
|
Sex string
|
|
Name string
|
|
}
|
|
type Student struct {
|
|
StudentID int
|
|
Person
|
|
}
|
|
|
|
s1 := Student{
|
|
StudentID: 1,
|
|
Sex: "male",
|
|
Name: "张三",
|
|
}
|
|
t.Log(s1)
|
|
}
|
|
|
|
func TestFeature2(t *testing.T) {
|
|
// Go 1.27 之前:必须手动写出类型实参 [int],否则编译报错
|
|
fn1 := IntToString(FormatToString[int])
|
|
fn2 := IntToString(FormatToString)
|
|
|
|
oldFormat := []IntToString{FormatToString[int]}
|
|
newFormat := []IntToString{FormatToString}
|
|
|
|
t.Log(fn1(1))
|
|
t.Log(fn2(2))
|
|
for i, fn := range oldFormat {
|
|
t.Log(fn(i))
|
|
}
|
|
for i, fn := range newFormat {
|
|
t.Log(fn(i))
|
|
}
|
|
|
|
}
|
|
|
|
// 一个泛型格式化函数
|
|
func FormatToString[T any](v T) string {
|
|
return fmt.Sprintf("value: %v", v)
|
|
}
|
|
|
|
// 具名函数类型:接收一个 int,返回 string
|
|
type IntToString func(int) string
|
|
|
|
func TestSort(t *testing.T) {
|
|
slice := []int{8, 2, 4, 4}
|
|
Sort1(slice)
|
|
t.Log(slice)
|
|
}
|
|
func Sort1(slice []int) {
|
|
for i := 0; i < len(slice)-1; i++ {
|
|
for j := 0; j < len(slice)-1-i; j++ {
|
|
if slice[j] > slice[j+1] {
|
|
slice[j], slice[j+1] = slice[j+1], slice[j]
|
|
}
|
|
}
|
|
}
|
|
}
|