【阶段1 Go语言基础】Day02 数组、切片、切片原理、map、字符串处理/字节切片、排序

发布时间 2023-05-30 00:54:50作者: 澐湮

第二天

流程控制

GOTO跳转

package main

import "fmt"

func main() {
	fmt.Println("start")
	goto END
	fmt.Println("1")
END:
	fmt.Println("end")
}

/*打印结果
D:\GoWork\src\go_course\day02>go run goto.go
start
end
*/
package main

import "fmt"

func main() {
	total := 0
	index := 0
	max := 100

START:
	index += 1
	total += index
	if index == max {
		goto END
	}
	goto START
END:
	fmt.Println(total)
}

/*打印结果
D:\GoWork\src\go_course\day02>go run total.go
5050
*/

break+lable 跳转

package main

import "fmt"

func main() {

BREAK:
	for z := 0; z < 2; z++ {
		fmt.Println(z, "*************")

		for j := 0; j < 3; j++ {
			fmt.Println(j, "----")
			for i := 0; i < 5; i++ {
				fmt.Println(i)
				if i == 3 {
					break BREAK
				}
			}
		}
	}
}

/*打印结构
D:\GoWork\src\go_course\day02>go run break.go
0 *************
0 ----
0
1
2
3
*/

continue+lable 跳转

package main

import "fmt"

func main() {

CONTINUE:
	for z := 0; z < 2; z++ {
		fmt.Println(z, "*************")

		for j := 0; j < 3; j++ {
			fmt.Println(j, "----")
			for i := 0; i < 5; i++ {
				fmt.Println(i)
				if i == 3 {
					continue CONTINUE
				}
			}
		}
	}
}

/*打印结果
D:\GoWork\src\go_course\day02>go run continue.go
0 *************
0 ----
0
1
2
3
1 *************
0 ----
0
1
2
3
*/

数组

声明

package main

import "fmt"

func main() {
	var names [3]string
	var signIns [3]bool
	var scores [3]float64
	//类型
	fmt.Printf("%T\n", names)
	fmt.Printf("%T\n", signIns)
	fmt.Printf("%T\n", scores)
	//零值
	fmt.Printf("%#v\n", names)
	fmt.Printf("%#v\n", signIns)
	fmt.Printf("%#v\n", scores)
}

/*打印结果
D:\GoWork\src\go_course\day02-20230214>go run array.go
[3]string
[3]bool
[3]float64
[3]string{"", "", ""}
[3]bool{false, false, false}
[3]float64{0, 0, 0}
*/

初始化

package main

import "fmt"

func main() {
	var names [3]string
	var signIns [3]bool
	var scores [3]float64
	//类型
	fmt.Printf("%T\n", names)
	fmt.Printf("%T\n", signIns)
	fmt.Printf("%T\n", scores)
	//零值
	fmt.Printf("%#v\n", names)
	fmt.Printf("%#v\n", signIns)
	fmt.Printf("%#v\n", scores)

	//字面量
	//第一种
	names = [3]string{"语文", "数学", "英语"}
	//第一种 扩展
	names = [...]string{"语文", "数学", "英语"}
	fmt.Printf("%#v\n", names)
	//第二种 注意结果,不是修改
	names = [3]string{1: "语文"}
	fmt.Printf("%#v\n", names)
}

/*打印结果
D:\GoWork\src\go_course\day02-20230214>go run array.go
[3]string
[3]bool
[3]float64
[3]string{"", "", ""}
[3]bool{false, false, false}
[3]float64{0, 0, 0}
[3]string{"语文", "数学", "英语"}
[3]string{"", "语文", ""}
*/

操作

关系运算 ==
package main

import "fmt"

func main() {
	var names [3]string
	var signIns [3]bool
	var scores [3]float64
	//类型
	fmt.Printf("%T\n", names)
	fmt.Printf("%T\n", signIns)
	fmt.Printf("%T\n", scores)
	//零值
	fmt.Printf("%#v\n", names)
	fmt.Printf("%#v\n", signIns)
	fmt.Printf("%#v\n", scores)

	//字面量
	//第一种
	names = [3]string{"语文", "数学", "英语"}
	//第二种
	names = [...]string{"语文", "数学", "英语"}
	fmt.Printf("%#v\n", names)
	//第三种 注意结果,不是修改
	names = [3]string{1: "语文"}
	fmt.Printf("%#v\n", names)
	
    //操作
    //关系运算
	fmt.Println(names == [3]string{})
	fmt.Println(names == [3]string{1: "语文"})
}

/*打印结果
D:\GoWork\src\go_course\day02-20230214>go run array.go
[3]string
[3]bool
[3]float64
[3]string{"", "", ""}
[3]bool{false, false, false}
[3]float64{0, 0, 0}
[3]string{"语文", "数学", "英语"}
[3]string{"", "语文", ""}
false
true
*/
元素访问和修改
package main

import "fmt"

func main() {
	var names [3]string
	var signIns [3]bool
	var scores [3]float64
	//类型
	fmt.Printf("%T\n", names)
	fmt.Printf("%T\n", signIns)
	fmt.Printf("%T\n", scores)
	//零值
	fmt.Printf("%#v\n", names)
	fmt.Printf("%#v\n", signIns)
	fmt.Printf("%#v\n", scores)

	//字面量
	//第一种
	names = [3]string{"语文", "数学", "英语"}
	//第二种
	names = [...]string{"语文", "数学", "英语"}
	fmt.Printf("%#v\n", names)
	//第三种 注意结果,不是修改
	names = [3]string{1: "语文"}
	fmt.Printf("%#v\n", names)

	//操作
	//关系运算
	fmt.Println(names == [3]string{})
	fmt.Println(names == [3]string{1: "语文"})

	//元素 访问和修改 索引
	fmt.Printf("%#v\n", names[0])
	// 修改元元素
	names[0] = "化学"
	fmt.Printf("%#v\n", names[0])
}

/*打印结果
D:\GoWork\src\go_course\day02-20230214>go run array.go
[3]string
[3]bool
[3]float64
[3]string{"", "", ""}
[3]bool{false, false, false}
[3]float64{0, 0, 0}
[3]string{"语文", "数学", "英语"}
[3]string{"", "语文", ""}
false
true
""
"化学"
*/
获取数组长度
package main

import "fmt"

func main() {
	var names [3]string
	var signIns [3]bool
	var scores [3]float64
	//类型
	fmt.Printf("%T\n", names)
	fmt.Printf("%T\n", signIns)
	fmt.Printf("%T\n", scores)
	//零值
	fmt.Printf("%#v\n", names)
	fmt.Printf("%#v\n", signIns)
	fmt.Printf("%#v\n", scores)

	//字面量
	//第一种
	names = [3]string{"语文", "数学", "英语"}
	//第二种
	names = [...]string{"语文", "数学", "英语"}
	fmt.Printf("%#v\n", names)
	//第三种 注意结果,不是修改
	names = [3]string{1: "语文"}
	fmt.Printf("%#v\n", names)

	//操作
	//关系运算
	fmt.Println(names == [3]string{})
	fmt.Println(names == [3]string{1: "语文"})

	//元素 访问和修改 索引
	fmt.Printf("%#v\n", names[0])
	// 修改元元素
	names[0] = "化学"
	fmt.Printf("%#v\n", names[0])

	//获取数组长度
	fmt.Printf("%#v\n", len(names))
}

/*打印结果
D:\GoWork\src\go_course\day02-20230214>go run array.go
[3]string
[3]bool
[3]float64
[3]string{"", "", ""}
[3]bool{false, false, false}
[3]float64{0, 0, 0}
[3]string{"语文", "数学", "英语"}
[3]string{"", "语文", ""}
false
true
""
"化学"
3
*/

遍历
package main

import (
	"fmt"
)

func main() {
	var names [3]string
	var signIns [3]bool
	var scores [3]float64
	//类型
	fmt.Printf("%T\n", names)
	fmt.Printf("%T\n", signIns)
	fmt.Printf("%T\n", scores)
	//零值
	fmt.Printf("%#v\n", names)
	fmt.Printf("%#v\n", signIns)
	fmt.Printf("%#v\n", scores)

	//字面量
	//第一种
	names = [3]string{"语文", "数学", "英语"}
	//第二种
	names = [...]string{"语文", "数学", "英语"}
	fmt.Printf("%#v\n", names)
	//第三种 注意结果,不是修改
	names = [3]string{1: "语文"}
	fmt.Printf("%#v\n", names)

	//操作
	//关系运算
	fmt.Println(names == [3]string{})
	fmt.Println(names == [3]string{1: "语文"})

	//元素 访问和修改 索引
	fmt.Printf("%#v\n", names[0])
	// 修改元元素
	names[0] = "化学"
	fmt.Printf("%#v\n", names[0])

	//获取数组长度
	fmt.Printf("%#v\n", len(names))

	//遍历
	for i := 0; i < len(names); i++ {
		fmt.Println(names[i])
	}

	for _, v := range names {
		fmt.Println(v)
	}
}

/*打印结果
D:\GoWork\src\go_course\day02-20230214>go run array.go
[3]string
[3]bool
[3]float64
[3]string{"", "", ""}
[3]bool{false, false, false}
[3]float64{0, 0, 0}
[3]string{"语文", "数学", "英语"}
[3]string{"", "语文", ""}
false
true
""
"化学"
3
化学
语文

化学
语文
*/

多维数组

声明和初始化
package main

import "fmt"

func main() {
	var students00 [6][8]string
	students01 := [...][2]string{{"aa", "a1"}, {"bb", "b1"}, {"cc", "c1"}}
	students02 := [3][3]string{{"aa", "a1", "a2"}, {"bb", "b1", "b2"}, {"cc", "c1", "c2"}}
	students03 := [3][3]string{0: {"aa", "a1", "a2"}, 2: {"cc", "c1", "c2"}}
	students04 := [3][3]string{0: {1: "a1", 2: "a2"}, 2: {1: "c1", 2: "c2"}}
	fmt.Printf("%T\n", students00)
	fmt.Printf("%q\n", students01)
	fmt.Printf("%q\n", students02)
	fmt.Printf("%q\n", students03)
	fmt.Printf("%#v\n", students04)
}

/*打印结果
D:\GoWork\src\go_course\day02-20230214>go run array2.go
[6][8]string
[["aa" "a1"] ["bb" "b1"] ["cc" "c1"]]
[["aa" "a1" "a2"] ["bb" "b1" "b2"] ["cc" "c1" "c2"]]
[["aa" "a1" "a2"] ["" "" ""] ["cc" "c1" "c2"]]
[3][3]string{[3]string{"", "a1", "a2"}, [3]string{"", "", ""}, [3]string{"", "c1", "c2"}}
*/

访问和修改
package main

import "fmt"

func main() {
	var students00 [6][8]string
	students01 := [...][2]string{{"aa", "a1"}, {"bb", "b1"}, {"cc", "c1"}}
	students02 := [3][3]string{{"aa", "a1", "a2"}, {"bb", "b1", "b2"}, {"cc", "c1", "c2"}}
	students03 := [3][3]string{0: {"aa", "a1", "a2"}, 2: {"cc", "c1", "c2"}}
	students04 := [3][3]string{0: {1: "a1", 2: "a2"}, 2: {1: "c1", 2: "c2"}}
	fmt.Printf("%T\n", students00)
	fmt.Printf("%q\n", students01)
	fmt.Printf("%q\n", students02)
	fmt.Printf("%q\n", students03)
	fmt.Printf("%#v\n", students04)
	//访问
	fmt.Println(students04[0][1])
	//修改
	students04[0][1] = "语文"
	fmt.Println(students04)
}

/*打印结果
D:\GoWork\src\go_course\day02-20230214>go run array2.go
[6][8]string
[["aa" "a1"] ["bb" "b1"] ["cc" "c1"]]
[["aa" "a1" "a2"] ["bb" "b1" "b2"] ["cc" "c1" "c2"]]
[["aa" "a1" "a2"] ["" "" ""] ["cc" "c1" "c2"]]
[3][3]string{[3]string{"", "a1", "a2"}, [3]string{"", "", ""}, [3]string{"", "c1", "c2"}}
a1
[[ 语文 a2] [  ] [ c1 c2]]
*/

切片

声明

package main

import "fmt"

func main() {
	var names []string
	//类型
	fmt.Printf("%T\n", names)

	//零值
	fmt.Printf("%#v\n", names)
}

/*打印结果
D:\GoWork\src\go_course\day02-20230214>go run slice.go
[]string
[]string(nil)
*/

初始化

package main

import "fmt"

func main() {
	var names []string
	//类型
	fmt.Printf("%T\n", names)

	//零值
	fmt.Printf("%#v\n", names)

	//初始化
	names = []string{}
	fmt.Printf("%#v\n", names)
	names = []string{"语文", "数学", "英语"}
	fmt.Printf("%#v\n", names)
	//第二种
	names = []string{1: "语文", 10: "数学"}
	fmt.Printf("%#v\n", names)
	//第三种 make函数
	names = make([]string, 5)
	fmt.Printf("%#v\n", names)
	names = make([]string, 0, 10)
	fmt.Printf("%#v\n", names)

}

/*打印结果
D:\GoWork\src\go_course\day02-20230214>go run slice.go
...
[]string{}
[]string{"语文", "数学", "英语"}
[]string{"", "语文", "", "", "", "", "", "", "", "", "数学"}
[]string{"", "", "", "", ""}
[]string{}
*/

操作

获取切片长度和容量
package main

import (
	"fmt"
)

func main() {
	var names []string
	//类型
	fmt.Printf("%T\n", names)

	//零值
	fmt.Printf("%#v\n", names)

	//初始化
	names = []string{}
	fmt.Printf("%#v\n", names)
	names = []string{"语文", "数学", "英语"}
	fmt.Printf("%#v\n", names)
	//第二种
	names = []string{1: "语文", 10: "数学"}
	fmt.Printf("%#v\n", names)
	//第三种 make函数
	names = make([]string, 5)
	fmt.Printf("%#v\n", names)
	names = make([]string, 0, 10)
	fmt.Printf("%#v\n", names)

	//索引
	names = make([]string, 3, 10)
	names[0] = "a"
	names[1] = "b"
	names[2] = "c"

	fmt.Println(names[0])
	fmt.Println(names[1])
	fmt.Println(names[2])
	fmt.Println(len(names), cap(names))
}

/*打印结果
D:\GoWork\src\go_course\day02-20230214>go run slice.go
...
a
b
c
3 10
*/

添加元素
package main

import (
	"fmt"
)

func main() {
	var names []string
	//类型
	fmt.Printf("%T\n", names)

	//零值
	fmt.Printf("%#v\n", names)

	//初始化
	names = []string{}
	fmt.Printf("%#v\n", names)
	names = []string{"语文", "数学", "英语"}
	fmt.Printf("%#v\n", names)
	//第二种
	names = []string{1: "语文", 10: "数学"}
	fmt.Printf("%#v\n", names)
	//第三种 make函数
	names = make([]string, 5)
	fmt.Printf("%#v\n", names)
	names = make([]string, 0, 10)
	fmt.Printf("%#v\n", names)

	//索引
	names = make([]string, 3, 10)
	names[0] = "a"
	names[1] = "b"
	names[2] = "c"

	fmt.Println(names[0])
	fmt.Println(names[1])
	fmt.Println(names[2])
	fmt.Println(len(names), cap(names))

	//添加元素
	names = append(names, "d")
	fmt.Printf("%#v\n", names)
	fmt.Println(len(names), cap(names))
}

/*打印结果
D:\GoWork\src\go_course\day02-20230214>go run slice.go
...
[]string{"a", "b", "c", "d"}
4 10
*/

遍历
package main

import (
	"fmt"
)

func main() {
	var names []string
	//类型
	fmt.Printf("%T\n", names)

	//零值
	fmt.Printf("%#v\n", names)

	//初始化
	names = []string{}
	fmt.Printf("%#v\n", names)
	names = []string{"语文", "数学", "英语"}
	fmt.Printf("%#v\n", names)
	//第二种
	names = []string{1: "语文", 10: "数学"}
	fmt.Printf("%#v\n", names)
	//第三种 make函数
	names = make([]string, 5)
	fmt.Printf("%#v\n", names)
	names = make([]string, 0, 10)
	fmt.Printf("%#v\n", names)

	//索引
	names = make([]string, 3, 10)
	names[0] = "a"
	names[1] = "b"
	names[2] = "c"

	fmt.Println(names[0])
	fmt.Println(names[1])
	fmt.Println(names[2])
	fmt.Println(len(names), cap(names))

	//添加元素
	names = append(names, "d")
	fmt.Printf("%#v\n", names)
	fmt.Println(len(names), cap(names))

	//遍历
	for i := 0; i < len(names); i++ {
		fmt.Println(names[i])
	}

	for i, v := range names {
		fmt.Println(i, v)
	}
}

/*打印结果
D:\GoWork\src\go_course\day02-20230214>go run slice.go
...
a
b
c
d
0 a
1 b
2 c
3 d
*/

复制切片
package main

import (
	"fmt"
)

func main() {
	var names []string
	//类型
	fmt.Printf("%T\n", names)

	//零值
	fmt.Printf("%#v\n", names)

	//初始化
	names = []string{}
	fmt.Printf("%#v\n", names)
	names = []string{"语文", "数学", "英语"}
	fmt.Printf("%#v\n", names)
	//第二种
	names = []string{1: "语文", 10: "数学"}
	fmt.Printf("%#v\n", names)
	//第三种 make函数
	names = make([]string, 5)
	fmt.Printf("%#v\n", names)
	names = make([]string, 0, 10)
	fmt.Printf("%#v\n", names)

	//索引
	names = make([]string, 3, 10)
	names[0] = "a"
	names[1] = "b"
	names[2] = "c"

	fmt.Println(names[0])
	fmt.Println(names[1])
	fmt.Println(names[2])
	fmt.Println(len(names), cap(names))

	//添加元素
	names = append(names, "d")
	fmt.Printf("%#v\n", names)
	fmt.Println(len(names), cap(names))

	//遍历
	for i := 0; i < len(names); i++ {
		fmt.Println(names[i])
	}

	for i, v := range names {
		fmt.Println(i, v)
	}

	// copy 切片之间赋值
	//目的 源 b 多
	aSlice := []string{"a", "b", "c"}
	bSlice := []string{"x", "y", "z", "m"}
	//长度相等
	copy(aSlice, bSlice)
	fmt.Printf("%#v %#v\n", aSlice, bSlice)

	aSlice = []string{"a", "b", "c"}
	bSlice = []string{"x", "y"}
	copy(aSlice, bSlice)
	fmt.Printf("%#v %#v\n", aSlice, bSlice)
}

/*打印结果
D:\GoWork\src\go_course\day02-20230214>go run slice.go
...
[]string{"x", "y", "z"} []string{"x", "y", "z", "m"}
[]string{"x", "y", "c"} []string{"x", "y"}
*/

切割切片
package main

import (
	"fmt"
)

func main() {
	var names []string
	//类型
	fmt.Printf("%T\n", names)

	//零值
	fmt.Printf("%#v\n", names)

	//初始化
	names = []string{}
	fmt.Printf("%#v\n", names)
	names = []string{"语文", "数学", "英语"}
	fmt.Printf("%#v\n", names)
	//第二种
	names = []string{1: "语文", 10: "数学"}
	fmt.Printf("%#v\n", names)
	//第三种 make函数
	names = make([]string, 5)
	fmt.Printf("%#v\n", names)
	names = make([]string, 0, 10)
	fmt.Printf("%#v\n", names)

	//索引
	names = make([]string, 3, 10)
	names[0] = "a"
	names[1] = "b"
	names[2] = "c"

	fmt.Println(names[0])
	fmt.Println(names[1])
	fmt.Println(names[2])
	fmt.Println(len(names), cap(names))

	//添加元素
	names = append(names, "d")
	fmt.Printf("%#v\n", names)
	fmt.Println(len(names), cap(names))

	//遍历
	for i := 0; i < len(names); i++ {
		fmt.Println(names[i])
	}

	for i, v := range names {
		fmt.Println(i, v)
	}

	// copy 切片之间赋值
	//目的 源 b 多
	aSlice := []string{"a", "b", "c"}
	bSlice := []string{"x", "y", "z", "m"}
	//长度相等
	copy(aSlice, bSlice)
	fmt.Printf("%#v %#v\n", aSlice, bSlice)

	aSlice = []string{"a", "b", "c"}
	bSlice = []string{"x", "y"}
	copy(aSlice, bSlice)
	fmt.Printf("%#v %#v\n", aSlice, bSlice)

	//切割切片
	s := "abcdef"
	fmt.Println(s[1:3])
	nums := []int{0, 1, 2, 3, 4, 5}
	fmt.Println(len(nums), cap(nums))
	nums = make([]int, 6, 10)
	fmt.Println(len(nums), cap(nums))

	numChildren := nums[3:7]
	fmt.Printf("%T %#v\n", numChildren, numChildren)
}

/*打印结果
D:\GoWork\src\go_course\day02-20230214>go run slice.go
...
bc
6 6
6 10
[]int []int{0, 0, 0, 0}
*/

切片副作用
package main

import (
	"fmt"
)

func main() {
	//切片副作用
	nums := []int{0, 1, 2, 3, 4, 5}
	numChildren := nums[3:4]
	numChildren = append(numChildren, 100)
	fmt.Println(nums, numChildren) 
}

/*打印结果
D:\GoWork\src\go_course\day02-20230214>go run slice.go
...
[0 1 2 3 100 5] [3 100]
*/

避免副作用
package main

import (
	"fmt"
)

func main() {
	//切片副作用
	nums := []int{0, 1, 2, 3, 4, 5}
	// numChildren := nums[3:4]
	// numChildren = append(numChildren, 100)
	// fmt.Println(nums, numChildren)

	//第一种 使用copy
	// numChildren := make([]int, len(nums[3:4]))
	// copy(numChildren, nums[3:4])
	// numChildren = append(numChildren, 100)
	// fmt.Println(nums, numChildren)

	//第二种 使用限制新切片容量值
	numChildren := nums[3:4:4]
	numChildren = append(numChildren, 100)
	fmt.Println(nums, numChildren)
}

/*打印结果
D:\GoWork\src\go_course\day02-20230214>go run slice.go
...
[0 1 2 3 4 5] [3 100]
*/

注意make的长度:
package main

import (
	"fmt"
)

func main() {
	//切片副作用
	nums := []int{0, 1, 2, 3, 4, 5}

	//可以make一个,再复制过来,需要注意make的长度
	// numChildren := make([]int, 0, 4) //numChildren=[]int{}
	// numChildren := make([]int, 4) //numChildren=[]int{0,0,0,0}
	numChildren := make([]int, len(nums[3:4])) //numChildren=[]int{0}
	copy(numChildren, nums[3:4])
	numChildren = append(numChildren, 100)
	fmt.Println(nums, numChildren)

}

/*打印结果
D:\GoWork\src\go_course\day02-20230214>go run slice.go
...
[0 1 2 3 4 5] [100]
[0 1 2 3 4 5] [3 0 0 0 100]
[0 1 2 3 4 5] [3 100]
*/

对数组切片

package main

import (
	"fmt"
)

func main() {
	numArray := [6]int{0, 1, 2, 3, 4, 5}
	arrayChildren := numArray[3:4]
	fmt.Printf("%T,%#v\n", arrayChildren, arrayChildren) //[]int,[]int{3}
	fmt.Println(cap(arrayChildren))                      //3
	arrayChildren = append(arrayChildren, 100)
	fmt.Println(numArray, arrayChildren) //[0 1 2 3 100 5] [3 100]
}

/*打印结果
D:\GoWork\src\go_course\day02-20230214>go run slice.go
[]int,[]int{3}
3
[0 1 2 3 100 5] [3 100]
*/

切片移除
package main

import (
	"fmt"
)

func main() {
	var names []string
	//类型
	fmt.Printf("%T\n", names)

	//零值
	fmt.Printf("%#v\n", names)

	//初始化
	names = []string{}
	fmt.Printf("%#v\n", names)
	names = []string{"语文", "数学", "英语"}
	fmt.Printf("%#v\n", names)
	//第二种
	names = []string{1: "语文", 10: "数学"}
	fmt.Printf("%#v\n", names)
	//第三种 make函数
	names = make([]string, 5)
	fmt.Printf("%#v\n", names)
	names = make([]string, 0, 10)
	fmt.Printf("%#v\n", names)

	//索引
	names = make([]string, 3, 10)
	names[0] = "a"
	names[1] = "b"
	names[2] = "c"

	fmt.Println(names[0])
	fmt.Println(names[1])
	fmt.Println(names[2])
	fmt.Println(len(names), cap(names))

	//添加元素
	names = append(names, "d")
	fmt.Printf("%#v\n", names)
	fmt.Println(len(names), cap(names))

	//遍历
	for i := 0; i < len(names); i++ {
		fmt.Println(names[i])
	}

	for i, v := range names {
		fmt.Println(i, v)
	}

	// copy 切片之间赋值
	//目的 源 b 多
	aSlice := []string{"a", "b", "c"}
	bSlice := []string{"x", "y", "z", "m"}
	//长度相等
	copy(aSlice, bSlice)
	fmt.Printf("%#v %#v\n", aSlice, bSlice)

	aSlice = []string{"a", "b", "c"}
	bSlice = []string{"x", "y"}
	copy(aSlice, bSlice)
	fmt.Printf("%#v %#v\n", aSlice, bSlice)

	//切割切片
	s := "abcdef"
	fmt.Println(s[1:3])
	// nums := []int{0, 1, 2, 3, 4, 5}
	// fmt.Println(len(nums), cap(nums))
	// nums = make([]int, 6, 10)
	// fmt.Println(len(nums), cap(nums))

	// numChildren := nums[3:7]
	// fmt.Printf("%T %#v\n", numChildren, numChildren)

	//切片副作用
	nums := []int{0, 1, 2, 3, 4, 5}
	// numChildren := nums[3:4]
	// numChildren = append(numChildren, 100)
	// fmt.Println(nums, numChildren)

	//第一种
	// numChildren := make([]int, len(nums[3:4]))
	// copy(numChildren, nums[3:4])
	// numChildren = append(numChildren, 100)
	// fmt.Println(nums, numChildren)

	//第二种
	// numChildren := nums[3:4:4]
	// fmt.Println(len(numChildren), cap(numChildren))
	// numChildren = append(numChildren, 100)
	// fmt.Println(nums, numChildren)

	//可以make一个,再复制过来,需要注意make的长度
	// numChildren := make([]int, 0, 4) //numChildren=[]int{}
	// numChildren := make([]int, 4) //numChildren=[]int{0,0,0,0}
	// numChildren := make([]int, len(nums[3:4])) //numChildren=[]int{0}
	// copy(numChildren, nums[3:4])
	// numChildren = append(numChildren, 100)
	// fmt.Println(nums, numChildren)

	// numArray := [6]int{0, 1, 2, 3, 4, 5}
	// arrayChildren := numArray[3:4]
	// fmt.Printf("%T,%#v\n", arrayChildren, arrayChildren) //[]int,[]int{3}
	// fmt.Println(cap(arrayChildren))                      //3
	// arrayChildren = append(arrayChildren, 100)
	// fmt.Println(numArray, arrayChildren) //[0 1 2 3 100 5] [3 100]

	//移除切片操作
	//第一个元素或最后一个元素
	//移除第一个元素
	nums = nums[1:]
	fmt.Println(nums)
	//移除最后一个元素
	nums = nums[:len(nums)-1]
	fmt.Println(nums)

	//移除中间的元素怎么办
	nums = []int{2, 3, 4}
	//[2 3 4]移除3(index)
	//切片操作copy
	//[index:] [3,4]
	//[index+1:] [4]
	//copy([index:],[index+1:]) [2,4,4]
	copy(nums[1:], nums[2:])
	nums = nums[:len(nums)-1]
	fmt.Println(nums)
}

/*打印结果
D:\GoWork\src\go_course\day02-20230214>go run slice.go
[1 2 3 4 5]
[1 2 3 4]
[2 4]
*/

队列
package main

import (
	"fmt"
)

func main() {
	//队列
	//先进先出
	queue := []string{}
	//push
	//append
	queue = append(queue, "a", "b")
	queue = append(queue, "c")
	//pop
	x := queue[0]
	queue = queue[1:]
	fmt.Println("1", x)
	x = queue[0]
	queue = queue[1:]
	fmt.Println("2", x)
	x = queue[0]
	queue = queue[1:]
	fmt.Println("3", x)
}

/*打印结果
D:\GoWork\src\go_course\day02-20230214>go run queue.go
1 a
2 b
3 c
*/

堆栈
package main

import (
	"fmt"
)

func main() {
	//堆栈
	//先进后出
	stack := []string{}
	//push
	//append
	stack = append(stack, "a")
	stack = append(stack, "b")
	stack = append(stack, "c")
	//pop
	//后面移除
	x := stack[len(stack)-1]
	stack = stack[:len(stack)-1]
	fmt.Println("发射", x)
	x = stack[len(stack)-1]
	stack = stack[:len(stack)-1]
	fmt.Println("发射", x)
	x = stack[len(stack)-1]
	stack = stack[:len(stack)-1]
	fmt.Println("发射", x)
}

/*打印结果
D:\GoWork\src\go_course\day02-20230214>go run stack.go
发射 c
发射 b
发射 a
*/

sort排序
package main

import (
	"fmt"
	"sort"
)

func main() {
	nums := []int{3, 2, 1, 6, 90, 7}
	sort.Ints(nums)
	fmt.Println(nums) //[1 2 3 6 7 90]

	names := []string{"abc", "xyz", "mn", "z", "k"}
	sort.Strings(names)
	fmt.Println(names) //[abc k mn xyz z]
}

/*打印结果
D:\GoWork\src\go_course\day02-20230214>go run sort.go
[1 2 3 6 7 90]
[abc k mn xyz z]
*/

sort倒序
package main

import (
	"fmt"
	"sort"
)

func main() {
	nums := []int{3, 2, 1, 6, 90, 7}
	sort.Sort(sort.Reverse(sort.IntSlice(nums)))
	fmt.Println(nums)
}

/*打印结果
D:\GoWork\src\go_course\day02-20230214>go run sort.go
[90 7 6 3 2 1]
*/

二分查找
package main

import (
	"fmt"
	"sort"
)

func main() {
	nums := []int{3, 2, 1, 6, 90, 7}
	// sort.Ints(nums)
	sort.Sort(sort.Reverse(sort.IntSlice(nums)))
	fmt.Println(nums) //[1 2 3 6 7 90]

	// names := []string{"abc", "xyz", "mn", "z", "k"}
	// sort.Strings(names)
	// fmt.Println(names) //[abc k mn xyz z]
	nums = []int{1, 3, 5, 9, 10}
	fmt.Println(sort.SearchInts(nums, 8)) //不存在,返回插入到索引3的位置
	fmt.Println(sort.SearchInts(nums, 5)) //存在,返回5对应的索引2
	fmt.Println(nums[sort.SearchInts(nums, 8)] == 8)
	fmt.Println(nums[sort.SearchInts(nums, 5)] == 5)

}
/*打印结果
D:\GoWork\src\go_course\day02-20230214>go run sort.go
3
2
false
true
*/

多维切片

package main

import "fmt"

func main() {
	multi := [][]string{}
	fmt.Printf("%T %#v\n", multi, multi)
	multi = append(multi, []string{"1", "2", "3"})
	multi = append(multi, []string{"1", "2", "3", "5"})
	fmt.Println(multi)
	fmt.Printf("%T %#v\n", multi[0], multi[0])
	fmt.Printf("%T %#v\n", multi[0][1], multi[0][1])
	multi[0][1] = "xyz"
	multi[1] = append(multi[1], "xxx")
	fmt.Println(multi)
}

/*打印结果
D:\GoWork\src\go_course\day02-20230214>go run multislice.go
[][]string [][]string{}
[[1 2 3] [1 2 3 5]]
[]string []string{"1", "2", "3"}
string "2"
[[1 xyz 3] [1 2 3 5 xxx]]
*/

nilslice
package main

import "fmt"

func main() {
	var nilSlice []int
	var emptySlice = []int{}
	fmt.Printf("%T %#v\n", nilSlice, nilSlice)
	fmt.Printf("%T %#v\n", emptySlice, emptySlice)
	nilSlice = append(nilSlice, 1)
	emptySlice = append(emptySlice, 1)
	fmt.Printf("%T %#v\n", nilSlice, nilSlice)
	fmt.Printf("%T %#v\n", emptySlice, emptySlice)
}

/*打印结果
D:\GoWork\src\go_course\day02-20230214>go run nilslice.go
[]int []int(nil)
[]int []int{}
[]int []int{1}
[]int []int{1}
*/

map

映射 由键值对组成一种数据结构,通过key来对value进行操作
	无序的数据结构
类型  map[keyType]valueType

声明

package main

import "fmt"

func main() {
	//每个同学的成绩
	//key => ID value =>成绩
	var scores map[string]float64
	fmt.Printf("%T %#v\n", scores, scores)
}

/*打印结果
D:\GoWork\src\go_course\day02-20230214>go run map.go
map[string]float64 map[string]float64(nil)
*/

初始化

package main

import (
	"fmt"
)

func main() {
	//每个同学的成绩
	//key => ID value =>成绩
	var scores map[string]float64
	fmt.Printf("%T %#v\n", scores, scores)

	//初始化
	scores = map[string]float64{}
	fmt.Printf("%T,%#v\n", scores, scores)
	scores = map[string]float64{"22": 80, "23": 90, "37": 70}
	fmt.Printf("%T %#v\n", scores, scores)

	//make
	scores = make(map[string]float64)
	fmt.Printf("%T %#v\n", scores, scores)
}

/*打印结果
D:\GoWork\src\go_course\day02-20230214>go run map.go
map[string]float64 map[string]float64(nil)
map[string]float64,map[string]float64{}
map[string]float64 map[string]float64{"22":80, "23":90, "37":70}
map[string]float64 map[string]float64{}
*/

操作

添加元素&获取长度
package main

import (
	"fmt"
)

func main() {
	//每个同学的成绩
	//key => ID value =>成绩
	var scores map[string]float64
	fmt.Printf("%T %#v\n", scores, scores)

	//初始化
	scores = map[string]float64{}
	fmt.Printf("%T,%#v\n", scores, scores)
	scores = map[string]float64{"22": 80, "23": 90, "37": 70}
	fmt.Printf("%T %#v\n", scores, scores)

	//make
	scores = make(map[string]float64)
	fmt.Printf("%T %#v\n", scores, scores)

	//操作
	scores = map[string]float64{"22": 80, "23": 90, "37": 70, "xx": 0}
	fmt.Println(len(scores))

}

/*打印结果
D:\GoWork\src\go_course\day02-20230214>go run map.go
map[string]float64 map[string]float64(nil)
map[string]float64,map[string]float64{}
map[string]float64 map[string]float64{"22":80, "23":90, "37":70}
map[string]float64 map[string]float64{}
4
*/

查找
package main

import (
	"fmt"
)

func main() {
	//每个同学的成绩
	//key => ID value =>成绩
	var scores map[string]float64
	//操作
	scores = map[string]float64{"22": 80, "23": 90, "37": 70, "xx": 0}

	//key => value
	//查找
	fmt.Println(scores["22"])
	fmt.Println(scores["XX"])
	fmt.Println(scores["yy"])
}

/*打印结果
D:\GoWork\src\go_course\day02-20230214>go run map.go
4
80
0
0
*/

判断key是否存在
package main

import (
	"fmt"
)

func main() {
	//每个同学的成绩
	//key => ID value =>成绩
	var scores map[string]float64
	//操作
	scores = map[string]float64{"22": 80, "23": 90, "37": 70, "xx": 0}
	fmt.Println(len(scores))

	//判断key是否存在
	v, ok := scores["yy"]
	fmt.Println(v, ok)
	v, ok = scores["xx"]
	fmt.Println(v, ok)
}

/*打印结果
D:\GoWork\src\go_course\day02-20230214>go run map.go
4
0 false
0 true
*/

修改&增加
package main

import (
	"fmt"
)

func main() {
	//每个同学的成绩
	//key => ID value =>成绩
	var scores map[string]float64
	fmt.Printf("%T %#v\n", scores, scores)

	//初始化
	scores = map[string]float64{}
	scores = map[string]float64{"22": 80, "23": 90, "37": 70, "xx": 0}

	//修改
	fmt.Println(scores)
	scores["xx"] = 100
	fmt.Println(scores["xx"])
	//增加
	scores["yy"] = 99
	fmt.Println(scores)
	scores["aa"] = 99
	fmt.Println(scores)
}

/*打印结果
D:\GoWork\src\go_course\day02-20230214>go run map.go
map[22:80 23:90 37:70 xx:0]
100
map[22:80 23:90 37:70 xx:100 yy:99]
map[22:80 23:90 37:70 aa:99 xx:100 yy:99]
*/

删除
package main

import (
	"fmt"
)

func main() {
	//每个同学的成绩
	//key => ID value =>成绩
	var scores map[string]float64
	scores = map[string]float64{"22": 80, "23": 90, "37": 70, "xx": 0}


	//修改
	scores["xx"] = 100
	//增
	scores["yy"] = 99
	scores["aa"] = 99
	fmt.Println(scores)

	//删除
	delete(scores, "yy")
	fmt.Println(scores)
	delete(scores, "bb")
	fmt.Println(scores)
}

/*打印结果
D:\GoWork\src\go_course\day02-20230214>go run map.go
map[22:80 23:90 37:70 xx:0]
map[22:80 23:90 37:70 aa:99 xx:100 yy:99]
map[22:80 23:90 37:70 aa:99 xx:100]
map[22:80 23:90 37:70 aa:99 xx:100]
*/

遍历
package main

import (
	"fmt"
)

func main() {
	//每个同学的成绩
	//key => ID value =>成绩
	var scores map[string]float64
	scores = map[string]float64{"22": 80, "23": 90, "37": 70, "xx": 0}
	for v := range scores {
		fmt.Println(v, scores[v])
	}
	for k, v := range scores {
		fmt.Println(k, v)
	}
}


/*打印结果
D:\GoWork\src\go_course\day02-20230214>go run map.go
37 70
xx 100
aa 99
22 80
23 90
xx 100
aa 99
22 80
23 90
37 70
*/

nilmap
package main

import "fmt"

func main() {
	var nilMap map[string]string
	fmt.Println(len(nilMap))
	fmt.Println(nilMap["kk"])
	fmt.Printf("%#v\n", nilMap)
}

/*打印结果
D:\GoWork\src\go_course\day02-20230214>go run nilmap.go
0

map[string]string(nil)
*/

优先级&& 高于 ||

package main

import "fmt"

func main() {
    // &&优先级大于 || 优先级
	var a, b, c, d int
	if a == 0 || c == 0 && d == 1 {
	//if (a == 0 || c == 0) && d == 1 {
		fmt.Println(a, b, c, d)
	}

}

/*打印结果
D:\GoWork\src\go_course\day02-20230214>go run priority.go
0 0 0 0
*/

练习 统计我有一个梦想单词数

package main

import "fmt"

/*
选班长:
   小红,小李,小新,小李,小新,小李,小李

   小红:1
   小李:4
   小新: 2
*/
//统计 我有一个梦想,每个英文(大小写区分)字母出现次数
func main() {
	//字符串
	article := `I am happy to join with you today in what will go down in history as the greatest demonstration for freedom in the history of our nation.
	Five score years ago, a great American, in whose symbolic shadow we stand today, signed the Emancipation Proclamation. This momentous decree came as a great beacon light of hope to millions of Negro slaves who had been seared in the flames of withering injustice. It came as a joyous daybreak to end the long night of bad captivity.
	But one hundred years later, the Negro still is not free. One hundred years later, the life of the Negro is still sadly crippled by the manacles of segregation and the chains of discrimination. One hundred years later, the Negro lives on a lonely island of poverty in the midst of a vast ocean of material prosperity. One hundred years later, the Negro is still languished in the corners of American society and finds himself an exile in his own land. And so we've come here today to dramatize a shameful condition.
	In a sense we've come to our nation's capital to cash a check. When the architects of our republic wrote the magnificent words of the Constitution and the Declaration of Independence, they were signing a promissory note to which every American was to fall heir. This note was a promise that all men, yes, black men as well as white men, would be guaranteed the "unalienable Rights" of "Life, Liberty and the pursuit of Happiness." It is obvious today that America has defaulted on this promissory note, insofar as her citizens of color are concerned. Instead of honoring this sacred obligation, America has given the Negro people a bad check, a check which has come back marked "insufficient funds."
	But we refuse to believe that the bank of justice is bankrupt. We refuse to believe that there are insufficient funds in the great vaults of opportunity of this nation. And so, we've come to cash this check, a check that will give us upon demand the riches of freedom and the security of justice.
	We have also come to this hallowed spot to remind America of the fierce urgency of Now. This is no time to engage in the luxury of cooling off or to take the tranquilizing drug of gradualism. Now is the time to make real the promises of democracy. Now is the time to rise from the dark and desolate valley of segregation to the sunlit path of racial justice. Now is the time to lift our nation from the quicksands of racial injustice to the solid rock of brotherhood. Now is the time to make justice a reality for all of God's children.
	It would be fatal for the nation to overlook the urgency of the moment. This sweltering summer of the Negro's legitimate discontent will not pass until there is an invigorating autumn of freedom and equality. Nineteen sixty-three is not an end, but a beginning. And those who hope that the Negro needed to blow off steam and will now be content will have a rude awakening if the nation returns to business as usual. And there will be neither rest nor tranquility in America until the Negro is granted his citizenship rights. The whirlwinds of revolt will continue to shake the foundations of our nation until the bright day of justice emerges.
	But there is something that I must say to my people, who stand on the warm threshold which leads into the palace of justice: In the process of gaining our rightful place, we must not be guilty of wrongful deeds. Let us not seek to satisfy our thirst for freedom by drinking from the cup of bitterness and hatred. We must forever conduct our struggle on the high plane of dignity and discipline. We must not allow our creative protest to degenerate into physical violence. Again and again, we must rise to the majestic heights of meeting physical force with soul force.
	The marvelous new militancy which has engulfed the Negro community must not lead us to a distrust of all white people, for many of our white brothers, as evidenced by their presence here today, have come to realize that their destiny is tied up with our destiny. And they have come to realize that their freedom is inextricably bound to our freedom.
	We cannot walk alone.
	And as we walk, we must make the pledge that we shall always march ahead.
	We cannot turn back.
	There are those who are asking the devotees of civil rights, "When will you be satisfied?" We can never be satisfied as long as the Negro is the victim of the unspeakable horrors of police brutality. We can never be satisfied as long as our bodies, heavy with the fatigue of travel, cannot gain lodging in the motels of the highways and the hotels of the cities. We cannot be satisfied as long as the Negro's basic mobility is from a smaller ghetto to a larger one. We can never be satisfied as long as our children are stripped of their selfhood and robbed of their dignity by signs stating "for whites only." We cannot be satisfied as long as a Negro in Mississippi cannot vote and a Negro in New York believes he has nothing for which to vote. No, no, we are not satisfied, and we will not be satisfied until "justice rolls down like waters, and righteousness like a mighty stream."
	I am not unmindful that some of you have come here out of great trials and tribulations. Some of you have come fresh from narrow jail cells. And some of you have come from areas where your quest -- quest for freedom left you battered by the storms of persecution and staggered by the winds of police brutality. You have been the veterans of creative suffering. Continue to work with the faith that unearned suffering is redemptive. Go back to Mississippi, go back to Alabama, go back to South Carolina, go back to Georgia, go back to Louisiana, go back to the slums and ghettos of our northern cities, knowing that somehow this situation can and will be changed.
	Let us not wallow in the valley of despair, I say to you today, my friends.
	And so even though we face the difficulties of today and tomorrow, I still have a dream. It is a dream deeply rooted in the American dream.
	I have a dream that one day this nation will rise up and live out the true meaning of its creed: "We hold these truths to be self-evident, that all man are created equal."
	I have a dream that one day on the red hills of Georgia, the sons of former slaves and the sons of former slave owners will be able to sit down together at the table of brotherhood.
	I have a dream that one day even the state of Mississippi, a state sweltering with the heat of injustice, sweltering with the heat of oppression, will be transformed into an oasis of freedom and justice.
	I have a dream that my four little children will one day live in a nation where they will not be judged by the color of their skin but by the content of their character.
	I have a dream today!
	I have a dream that one day, down in Alabama, with its vicious racists, with its governor having his lips dripping with the words of "interposition" and "nullification" -- one day right there in Alabama little black boys and black girls will be able to join hands with little white boys and white girls as sisters and brothers.
	I have a dream today!
	I have a dream that one day every valley shall be exalted, and every hill and mountain shall be made low, the rough places will be made plain, and the crooked places will be made straight; "and the glory of the Lord shall be revealed and all flesh shall see it together."
	This is our hope, and this is the faith that I go back to the South with.
	With this faith, we will be able to hew out of the mountain of despair a stone of hope. With this faith, we will be able to transform the jangling discords of our nation into a beautiful symphony of brotherhood. With this faith, we will be able to work together, to pray together, to struggle together, to go to jail together, to stand up for freedom together, knowing that we will be free one day.
	And this will be the day -- this will be the day when all of God's children will be able to sing with new meaning:
	My country 'tis of thee, sweet land of liberty, of thee I sing.
	Land where my fathers died, land of the Pilgrim's pride,
	From every mountainside, let freedom ring!
	And if America is to be a great nation, this must become true.
	And so let freedom ring from the prodigious hilltops of New Hampshire.
	Let freedom ring from the mighty mountains of New York.
	Let freedom ring from the heightening Alleghenies of
	Pennsylvania.
	Let freedom ring from the snow-capped Rockies of Colorado.
	Let freedom ring from the curvaceous slopes of California.
	But not only that:
	Let freedom ring from Stone Mountain of Georgia.
	Let freedom ring from Lookout Mountain of Tennessee.
	Let freedom ring from every hill and molehill of Mississippi.
	From every mountainside, let freedom ring.
	And when this happens, when we allow freedom ring, when we let it ring from every village and every hamlet, from every state and every city, we will be able to speed up that day when all of God's children, black men and white men, Jews and Gentiles, Protestants and Catholics, will be able to join hands and sing in the words of the old Negro spiritual:
	Free at last! Free at last!
	Thank God Almighty, we are free at last!`
	//遍历英文字母 for range
	stat := map[rune]int{}
	for _, ch := range article {
		if ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' {
			stat[ch]++
		}
	}
	fmt.Println(stat)
	for ch, cnt := range stat {
		fmt.Printf("%c %d\n", ch, cnt)
	}
}

/*打印结果
D:\GoWork\src\go_course\day02-20230214>go run charstat.go
map[65:27 66:4 67:6 68:1 69:1 70:5 71:9 72:2 73:23 74:1 76:15 77:7 78:25 79:3 80:4 82:2 83:4 84:10 87:17 89:3 97:541 98:112 99:176 100:269 101:887 102:219 103:166 104:382 105:542 106:20 107:51 108:327 109:181 110:460 111:604 112:92 113:7 114:411 115:425 116:661 117:176 118:81 119:148 120:5 121:125 122:6]
s 425
D 1
q 7
M 7
y 125
l 327
v 81
T 10
N 25
k 51
L 15
H 2
p 92
f 219
F 5
c 176
O 3
W 17
R 2
G 9
I 23
o 604
w 148
b 112
E 1
x 5
r 411
Y 3
a 541
m 181
i 542
P 4
j 20
u 176
d 269
g 166
z 6
C 6
h 382
t 661
n 460
e 887
A 27
B 4
S 4
J 1
*/

扩展
package main

import "fmt"

func main() {
	//字符串
	article := `I am happy to join with you today in what will go down in history as the greatest demonstration for freedom in the history of our nation.
	Five score years ago, a great American, in whose symbolic shadow we stand today, signed the Emancipation Proclamation. This momentous decree came as a great beacon light of hope to millions of Negro slaves who had been seared in the flames of withering injustice. It came as a joyous daybreak to end the long night of bad captivity.
	But one hundred years later, `
    //遍历英文字母 for range
	stat := map[rune]int{}
	for _, ch := range article {
		if ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' {
			stat[ch]++
		}
	}
	fmt.Println(stat)
    // 排序
	//先定义一个切片 a-zA-Z
	var keys = []rune{}
	for word := 'a'; word <= 'z'; word++ {
		keys = append(keys, word)
	}
	for word := 'A'; word <= 'Z'; word++ {
		keys = append(keys, word)
	}
	fmt.Println(keys)
	//以切片的元素为键,获取map值
	for _, key := range keys {
		fmt.Printf("%c,%#v\n", key, stat[key])
	}
    
    /*
    // 排序
	var keys = []int{}
	for k := range stat {
		keys = append(keys, int(k))
	}

	sort.Ints(keys)
	fmt.Println(keys)
	//以切片的元素为键,获取map值
	for _, key := range keys {
		fmt.Printf("%c,%#v\n", key, stat[rune(key)])
	}
    */

}



map按键排序
package main

import (
   "fmt"
   "sort"
)

func main() {
   //待排序队列
   var stuScore = map[int]string{1:"ee",5:"cc",4:"ff",9:"qq",3:"aa",2:"bb"}
   fmt.Println(stuScore) //map[1:ee 2:bb 3:aa 4:ff 5:cc 9:qq]

   nums:=make([]int,0)
   for k:=range stuScore{
      nums=append(nums,k)
   }
   sort.Sort(sort.Reverse(sort.IntSlice(nums)))
   fmt.Println(nums) //[9 5 4 3 2 1]

   for _,num:=range nums {
      fmt.Println(num,stuScore[num])
   }
}

//

map按值排序
package main
 
import (
    "fmt"
    "sort"
)
 
func main() {
    //待排序队列
    var stuScore = map[string]int{"ee":20,"cc":90,"ff":70,"qq":40,"aa":79,"bb":30}
     
    //创建切片,遍历map的值
    var nums = []int{}
    for _,v:=range stuScore {
        nums=append(nums,v)
    }
    //对切片按值排序
    //sort.Ints(nums)
    sort.Sort(sort.Reverse(sort.IntSlice(nums)))
    fmt.Println(nums)
     
    for _,num:=range nums {
        //遍历map的key和值,与切片中的元素做比对
        for k,v:=range stuScore {
            if v==num {
                // fmt.Println(k,v)
                sliStuScore = append(sliStuScore, map[string]int{k: v})
            }
        }
    }
 	fmt.Println(sliStuScore)
}
D:\GoWork\src\go_course\day02-20230214>go run mapvaluesort.go
[90 79 70 40 30 20]
[map[cc:90] map[aa:79] map[ff:70] map[qq:40] map[bb:30] map[ee:20]]


字符串转换

字符串和字节切片转换

package main

import (
	"fmt"
	"unicode/utf8"
)

func main() {
	ascii := "abc 我爱中华人民共和国"
	fmt.Println([]byte(ascii))
	fmt.Println([]rune(ascii))
	fmt.Println(len(ascii))
	fmt.Println(len([]rune(ascii)))
	fmt.Println(utf8.RuneCountInString(ascii))
	fmt.Println(string([]byte(ascii)))
	fmt.Println(string([]rune(ascii)))
}

/*打印结果
D:\GoWork\src\go_course\day02-20230214>go run string.go
[97 98 99 32 230 136 145 231 136 177 228 184 173 229 141 142 228 186 186 
230 176 145 229 133 177 229 146 140 229 155 189]
[97 98 99 32 25105 29233 20013 21326 20154 27665 20849 21644 22269]
31
13
13
abc 我爱中华人民共和国
abc 我爱中华人民共和国
*/

package main

import (
	"fmt"
	"strconv"
	"unicode/utf8"
)

func main() {
	ascii := "abc 我爱中华人民共和国"
	fmt.Println([]byte(ascii))
	fmt.Println([]rune(ascii))
	fmt.Println(len(ascii))
	fmt.Println(len([]rune(ascii)))
	fmt.Println(utf8.RuneCountInString(ascii))
	fmt.Println(string([]byte(ascii)))
	fmt.Println(string([]rune(ascii)))

	//int float bool
	fmt.Println(strconv.Itoa('a'))
	ch, err := strconv.Atoi("97")
	fmt.Println(ch, err)
	fmt.Println(strconv.FormatFloat(3.141592653, 'f', 10, 64))
	pi, err := strconv.ParseFloat("3.1415926", 64)
	fmt.Println(pi, err)

	fmt.Println(strconv.FormatBool(true))
	fmt.Println(strconv.ParseBool("true"))

	b, err := strconv.ParseInt("65535", 10, 8)
	fmt.Println(b, err)
	fmt.Println(strconv.FormatInt(15, 16))
	fmt.Println(strconv.FormatInt(15, 2))
}

/*打印结果
D:\GoWork\src\go_course\day02-20230214>go run string.go
[97 98 99 32 230 136 145 231 136 177 228 184 173 229 141 142 228 186 186 
230 176 145 229 133 177 229 146 140 229 155 189]
[97 98 99 32 25105 29233 20013 21326 20154 27665 20849 21644 22269]
31
13
13
abc 我爱中华人民共和国
abc 我爱中华人民共和国
97
97 <nil>
3.1415926530
3.1415926 <nil>
true
true <nil>
127 strconv.ParseInt: parsing "65535": value out of range
f
1111
*/

字符串比较

&包含

&计算次数

package main

import (
	"fmt"
	"strings"
)

func main() {
	//比较
	fmt.Println(strings.Compare("a", "b"))
	fmt.Println(strings.Compare("a", "a"))
	fmt.Println(strings.Compare("b", "a"))

	//包含
	fmt.Println(strings.Contains("我是xx", "xx"))
	fmt.Println(strings.Contains("我是xx", "xx1"))
	//只要包含一个就是true
	fmt.Println(strings.ContainsAny("我是xx", "xx"))
	fmt.Println(strings.ContainsAny("我是xx", "xx1"))
	fmt.Println(strings.ContainsRune("我是xx", '我'))
	fmt.Println(strings.ContainsRune("我是xx", 'a'))
	//计算次数
	fmt.Println(strings.Count("我是xx", "xx"))
	fmt.Println(strings.Count("我是xx", "x"))
	fmt.Println(strings.Count("我是xx", "xxa"))

}

/* 打印结果
D:\GoWork\src\go_course\day02-20230214>go run strings.go
-1
0
1
true
false
true
true
true
false
1
2
0
*/

比较(不区分大小写)

&分割(按空白)

&是否以开头、结尾

package main

import (
	"fmt"
	"strings"
)

func main() {
	//不区分大小写比较
	fmt.Println(strings.EqualFold("abc", "ABC"))
	fmt.Println(strings.EqualFold("abc", "ab"))
	fmt.Println(strings.EqualFold("abc", "XYZ"))

	//分割 空白符:空格 tab 回车 换行 换页...
	fmt.Printf("%#v\n", strings.Fields("a b\tc\rd\ne\ff"))
	//开头HasPrefix 结尾HasSuffix
	fmt.Println(strings.HasPrefix("abc", "ab"))
	fmt.Println(strings.HasSuffix("abc", "bc"))
}

/*打印结果
D:\GoWork\src\go_course\day02-20230214>go run strings.go
true
false
false
[]string{"a", "b", "c", "d", "e", "f"}
true
true
*/

字符串出现的位置index &LastIndex

&连接&分割

&重复&替换

package main

import (
	"fmt"
	"strings"
)

func main() {
	// 字符串出现的位置 index &LastIndex
	fmt.Println(strings.Index("abcdefdef", "def"))
	fmt.Println(strings.Index("abcdefdef", "xxx"))
	fmt.Println(strings.LastIndex("abcdefdef", "def"))

	//连接&分割
	fmt.Println(strings.Join([]string{"ab", "cd", "ef"}, "-"))
	fmt.Println(strings.Split("ab-cd-ef", "-"))
	fmt.Println(strings.SplitN("ab-cd-ef", "-", 2))

	//重复&替换
	fmt.Println(strings.Repeat("*", 5))
	fmt.Println(strings.Replace("xyzxyzxxxxyz", "yz", "mn", -1)) //-1替换全部
	fmt.Println(strings.Replace("xyzxyzxxxxyz", "yz", "mn", 1))
	fmt.Println(strings.ReplaceAll("xyzxyzxxxxy", "yz", "mn"))

}
/*打印结果
D:\GoWork\src\go_course\day02-20230214>go run strings.go
3
-1
6
ab-cd-ef
[ab cd ef]
[ab cd-ef]
*****
xmnxmnxxxxmn
xmnxyzxxxxyz
xmnxmnxxxxy
*/

行首行尾去除Trim

package main

import (
	"bytes"
	"fmt"
	"strings"
)

func main() {
	//Trim
	fmt.Println(strings.Trim("abcabcdefabcabc", "abc"))
	fmt.Println(strings.TrimLeft("cabcdefabc", "abc"))
	fmt.Println(strings.TrimRight("cabcdefabcda", "abc"))
	fmt.Println(strings.TrimPrefix("abccabcdefabc", "abc")) //字符串看做一个整体
	fmt.Println(strings.TrimSuffix("abccabcdefabc", "abc"))

	fmt.Println(bytes.Compare([]byte("abc"), []byte("xyz")))
}

/*
D:\GoWork\src\go_course\day02-20230214>go run strings.go
def
defabc
cabcdefabcd
cabcdefabc
abccabcdef
-1
*/

常见排序算法

冒泡排序

heighs=[]int{168,180,166,170,169}
第一次 heighs[0]、  heighs[1] 不交换 	[]int{168,180,  166,170,169}
第二次 heights[1]、 heighs[2] 交换	[]int{168,166,180,  170,169}
第三次 heights[2]、 heighs[3] 交换	[]int{168,166,170,180,  169}
第四次 heights[3]、 heighs[4] 交换	[]int{168,166,170,169,180  }

先将最高的排到队尾
算法:总是从第一个开始比较,如果前面的人高,交换两个人位置

package main

import "fmt"

func main() {
	// //交换
	// a, b := 1, 2
	// a, b = b, a
	// fmt.Println(a, b)
	heighs := []int{168, 180, 166, 176, 169}

	//第一轮
	// for i := 0; i < len(heighs)-1; i++ {
	// 	if heighs[i] > heighs[i+1] {
	// 		heighs[i], heighs[i+1] = heighs[i+1], heighs[i]

	// 	}
	// 	fmt.Println(i, heighs)
	// }
	// fmt.Println(heighs)

	//执行 len(heighs)-1 次
	for j := 0; j < len(heighs)-1; j++ {
		for i := 0; i < len(heighs)-1-j; i++ { //每轮少比一次行不行?
			// for i := 0; i < len(heighs)-1; i++ {
			if heighs[i] > heighs[i+1] {
				heighs[i], heighs[i+1] = heighs[i+1], heighs[i]
			}
			fmt.Println(i, heighs)
		}
		fmt.Println(heighs)
	}
	fmt.Println("over", heighs)
}

/*打印结果
D:\GoWork\src\go_course\day02-20230214>go run bubbleSort.go
0 [168 180 166 176 169]
1 [168 166 180 176 169]   
2 [168 166 176 180 169]   
3 [168 166 176 169 180]   
[168 166 176 169 180]     
0 [166 168 176 169 180]   
1 [166 168 176 169 180]   
2 [166 168 169 176 180]   
[166 168 169 176 180]     
0 [166 168 169 176 180]   
1 [166 168 169 176 180]   
[166 168 169 176 180]     
0 [166 168 169 176 180]   
[166 168 169 176 180]     
over [166 168 169 176 180]
*/

选择排序

介绍
	选择排序也属于内部排序法,按指定规则选出某一元素,经过和其他元素重整,再依原则交换位置后达到排序的目的

选择排序思路分析图
	初始状态 【 \8  3  2  \1  7  4  6  5 】
	第1次   【 1  \3  \2  8  7  4  6  5 】
	第二次	 【 1  2  \3  5  7  4  6  5 】
	第三次	 【 1  2  3  \8  7  \4  6  5 】
	第四次	 【 1  2  3  4  \7  8  6  \5 】
	第五次	 【 1  2  3  4  5  \8  \6  7 】
	第六次	 【 1  2  3  4  5  6  \8  \7 】
	第七次	 【 1  2  3  4  5  6  7  8 】

代码实现
package main

import "fmt"

func SelectSort(arr *[8]int) {
	//标准的访问方式
	// (*arr)[1] = 100 等价于 arr[1] = 900
	//1 先完成将第一个最小值和arr[0] =>先易后难
	//1 假设array[0]最小
	min := arr[0]
	minIndex := 0
	//2 遍历后面 1 -- [len(n)-1]比较
	for i := 0 + 1; i < len(arr); i++ {
		if arr[i] < min {
			min = arr[i]
			minIndex = i
		}
	}
	//交换
	if minIndex != 0 {
		arr[0], arr[minIndex] = arr[minIndex], arr[0]
	}
	fmt.Println("第1次", arr)

	//第二次
	min = arr[1]
	minIndex = 1
	//2 遍历后面 1 -- [len(n)-1]比较
	for i := 1 + 1; i < len(arr); i++ {
		if arr[i] < min {
			min = arr[i]
			minIndex = i
		}
	}
	//交换
	if minIndex != 1 {
		arr[1], arr[minIndex] = arr[minIndex], arr[1]
	}
	fmt.Println("第2次", arr)

	//第n次 8位数 比7次 n=7
	for j := 0; j < len(*arr)-1; j++ {
		min = arr[j]
		minIndex = j
		//2 遍历后面 1 -- [len(n)-1]比较
		for i := j + 1; i < len(arr); i++ {
			if arr[i] < min {
				min = arr[i]
				minIndex = i
			}
		}
		//交换
		if minIndex != j {
			arr[j], arr[minIndex] = arr[minIndex], arr[j]
		}
		fmt.Printf("第%d次 %v\n", j+1, arr)
	}
}

func main() {
	//定义一个数组,从小到大
	arr := [8]int{8, 3, 2, 1, 7, 4, 6, 5}
	SelectSort(&arr)
	fmt.Println(arr)
}

/*打印结果
D:\GoWork\src\go_course\day02-20230214>go run selectSort.go
第1次 &[1 3 2 8 7 4 6 5]
第2次 &[1 2 3 8 7 4 6 5]
第1次 &[1 2 3 8 7 4 6 5]
第2次 &[1 2 3 8 7 4 6 5]
第3次 &[1 2 3 8 7 4 6 5]
第4次 &[1 2 3 4 7 8 6 5]
第5次 &[1 2 3 4 5 8 6 7]
第6次 &[1 2 3 4 5 6 8 7]
第7次 &[1 2 3 4 5 6 7 8]
[1 2 3 4 5 6 7 8] 
*/

插入排序

介绍
	插入排序属于内部排序法,把n个待排序元素看成一个有序表和一个无序表
	开始有序表中1个元素,无序表中n-1个元素。
	从无序表取元素,插入有序表中
思路图
	原始数组           【23】 0   12  56  34
	第一次找到插入位置  【23, 0】 12  56  34 
	第二次找到插入位置  【23,  => 0】 56  34
					 【23,12, 0】 56  34
	第三次找到插入位置  【23,12, => 0】  34
					 【23, => 12,0】  34
					 【 => 23, 12,0】 34
					 【56,23,12,0】  34
	第四次找到插入位置  【56,23,12, => 0】
					 【56,23, => 12,0】
					 【56, => 23,12,0】
					 【56,34,23,12,0】

代码实现
package main

import "fmt"

func InsertSort(arr *[5]int) {
	// //完成第一次,给第二元素找到合适的位置并插入
	// insertVal := arr[1]
	// insertIndex := 1 - 1

	// //从大到小
	// for insertIndex >= 0 && arr[insertIndex] < insertVal {
	// 	arr[insertIndex+1] = arr[insertIndex] //数据后移
	// 	insertIndex--
	// }
	// //插入
	// if insertIndex+1 != 1 {
	// 	arr[insertIndex] = insertVal
	// }
	// fmt.Println("第一次插入后", *arr)

	// //完成第2次,给第3个元素找到合适的位置并插入
	// insertVal = arr[2]
	// insertIndex = 2 - 1 //下标
	// //从大到小
	// for insertIndex >= 0 && arr[insertIndex] < insertVal {
	// 	arr[insertIndex+1] = arr[insertIndex]
	// 	insertIndex--
	// }
	// //插入
	// if insertIndex+1 != 2 {
	// 	arr[insertIndex+1] = insertVal
	// }
	// fmt.Println("第2次插入后", *arr)

	for i := 1; i < len(arr); i++ {
		insertVal := arr[i]
		insertIndex := i - 1 //下标
		//从大到小
		for insertIndex >= 0 && arr[insertIndex] < insertVal {
			arr[insertIndex+1] = arr[insertIndex]
			insertIndex--
		}
		//插入
		if insertIndex+1 != i {
			arr[insertIndex+1] = insertVal
		}
		fmt.Printf("第%d次插入后%v\n", i, *arr)
	}

}

func main() {
	arr := [5]int{23, 0, 12, 56, 34}
	fmt.Println("原始数组=", arr)
	InsertSort(&arr)
	fmt.Println("main 函数")
	fmt.Println(arr)
}

/*打印结果
D:\GoWork\src\go_course\day02-20230214>go run InsertSort.go
原始数组= [23 0 12 56 34]
第1次插入后[23 0 12 56 34]
第2次插入后[23 12 0 56 34]
第3次插入后[56 23 12 0 34]
第4次插入后[56 34 23 12 0]
main 函数
[56 34 23 12 0]
*/

*快速排序

介绍
	快速排序是对冒泡排序的一种改进。基本思路:通过一趟排序将要排序的数据分割成独立的两部分,一部分所有数据比另一部分所有数据都小,然后按此方法对这两部分数据分别进行快速排序,整个过程可以递归进行,以此达到整个数据变成有序序列

【-9, 78, 0, 23, -567, 70】
以0位基准
	 -9 -567        0         23 78 70
左边以-567位基准,右边以78为基准。小的放左边,大的放右边
        -567 -9     0       23 70 78   

左l:=0
右r:=5
中轴pivot:=2
临时temp:=0
目标:小的放左边,大放右边
第一轮 从左边找大于pivot值 array[1]=78
	  从右边找小于pivot值 array[4]=-567
	  找到l>=r 退出,本次分解任务完成。
	  
	  交换:array[l],array[r] = array[r],array[l]
	优化: array[l]与array[r]交换后 array[l]相当于array[r]的位置
	  



package main

import "fmt"

//快速排序
func QuickSort(left int, right int, array *[9]int) {
	l := left
	r := right
	// pivot是中轴,支点
	pivot := array[(left+right)/2]
	temp := 0

	//for循环的目标是将比pivot小的数放到左边
	// 比pivot大的数放到 右边
	for l < r {
		//从 pivot的左边找到大于等于pivot的值
		for array[l] < pivot {
			l++
		}
		//从 pivot的右边找到大于等于pivot的值
		for array[r] > pivot {
			r--
		}
		// l>=r表名本次分解任务完成,break
		if l >= r {
			break
		}

		//交换
		temp = array[l]
		array[l] = array[r]
		array[r] = temp
		//优化(array[l]和arrar[r]交换,所以array[l]相当于array[r]的位置,位置再移)
		if array[l] == pivot {
			r--
		}
		if array[r] == pivot {
			l++
		}
	}
	//如果l==r,再移动下
	if l == r {
		l++
		r--
	}
	//向左递归
	if left < r {
		QuickSort(left, r, array)
	}
	//向右递归
	if right > l {
		QuickSort(l, right, array)
	}

}

func main() {
	// arr := [6]int{-9, 78, 0, 23, -567, 70}
	arr := [9]int{-9, 78, 0, 23, -567, 70, 123, 90, -23}
	//调用快速排序
	QuickSort(0, len(arr)-1, &arr)
	fmt.Println(arr)
}

/*打印结果
D:\GoWork\src\go_course\day02-20230214>go run quickSort.go 
[-567 -23 -9 0 23 70 78 90 123]
*/