数组 array
package main
import "fmt"
func main() {
number1 := [3]int{1, 2, 2: 3}
number2 := [3][4]int{
{1, 2, 3, 4},
{5, 6, 7, 8},
{0: 9, 1: 10, 2: 11, 3: 12},
}
number3 := [2][2][3]int{
{{1, 2, 3}, {4, 5, 6}},
{{7, 8, 9}, {10, 11, 12}},
}
fmt.Println(number1)
fmt.Println(number2)
fmt.Println(number3)
number4 := [...]int{3, 1, 9, 6, 8}
for i := 0; i < len(number4); i++ {
for j := i + 1; j < len(number4); j++ {
if number4[i] < number4[j] {
number4[i], number4[j] = number4[j], number4[i]
}
}
}
fmt.Println(number4)
}
[1 2 3]
[[1 2 3 4] [5 6 7 8] [9 10 11 12]]
[[[1 2 3] [4 5 6]] [[7 8 9] [10 11 12]]]
[9 8 6 3 1]
切片 slice
package main
import "fmt"
func main() {
//`len` 获取`slice`的长度, `cap` 获取`slice`的最大容量
number1 := make([]int, 9, 10)
fmt.Println(len(number1), cap(number1))
number2 := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
number3 := number2[:6]
number4 := number2[6:]
number5 := number2[4:5]
fmt.Println(number3, number4, number5)
}
9 10
[1 2 3 4 5 6] [7 8 9] [5]
集合 map
package main
import (
"fmt"
"sort"
)
func main() {
number3 := map[int]string{1: "a", 2: "b", 3: "c", 4: "d", 5: "e"}
number4 := make([]int, len(number3))
i := 0
for k, v := range number3 {
fmt.Println(k, v)
number4[i] = k
i++
}
sort.Ints(number4)
fmt.Println(number4)
}
2 b
3 c
4 d
5 e
1 a
[1 2 3 4 5]
3 c
4 d
5 e
1 a
2 b
[1 2 3 4 5]
通道 channel
package main
import "fmt"
func main() {
//使用 make(chan val-type) 创建一个新的通道
ch := make(chan int)
//go 关键字创建一个协程
go loop(ch)
go loop(ch)
//使用阻塞的接受方式来等待一个 go 协程的运行结束
<-ch
<-ch //从通道中接收值
}
func loop(ch chan int) {
for i := 0; i < 8; i++ {
fmt.Println(i)
}
ch <- 1 //发送值到通道
}
相关阅读