阅读 52

Golang数组&切片&map---关键点

1、数组的声明和初始化

//声明一个int型的数组
var arr [5]int
arr := [5]int
复制代码

遍历一个数组

for i:=0;i<len(arr);i++ {
	a[i]=0
}
for i:=0;i<len(arr);i++ {
	fmt.Printf("Array at index %d is %d\n",i,arr[i])
//for-range
for i,_:= range arr1 {
	arr[i]=0
}
复制代码

new()创建数组

var arr = new([5]int)//------指针类型*[5]int
var arr [5]int//------值类型[5]int
复制代码

2、数组常量声明

var arr = [5]int{1,2,3,4,5}//1 2 3 4 5
var arr = [5]int{1,2,3}//1 2 3 0 0
var arr = [5]string{2:"a",4:"b"}//_ _ a _ b (按索引值排)
复制代码

3、多维数组

package main
const (
	WIDTH  = 5
	HEIGHT = 4
)
type pixel int
var double[WIDTH][HEIGHT]pixel
func main() {
	for y := 0; y < HEIGHT; y++ {
		for x := 0; x < WIDTH; x++ {
			double[x][y] = 0
		}
	}
}
复制代码

4、切片声明 切片是对数组的连续片段的引用(指针类型,不要再取地址)切片提供了一个相关数组的动态窗口,切片是一个 长度可变的数组(更常用)

var slice []int = arr[start:end]
var slice []int = arr[:]//从头到尾 即var slice [] int = arr[0:len(arr)]
var slice []int = arr[2:]//即arr[2:len(arr)] 从第三个到最后一个
var slice []int = arr[:3]//即arr[0:3] 从第一个到第三个(不包括第四个!)
复制代码

想遍历输出切片时,小心 “:”后的数!是索引数,但是没有包含第+1个(以切片取整个数组为例)

package main
import "fmt"
func main() {
    arr:= []byte{'g', 'o', 'l', 'a', 'n', 'g'}
    x:=arr[0:5]
    for i:=0;i<len(x);i++{
         fmt.Printf("%c",x[i])   
    }
}
//output:golan
复制代码

确实不包括第6个字符哦!如果想完整输出,那么就严格按照定义[0:len(arr)]

package main
import "fmt"
func main() {
    arr:= []byte{'g', 'o', 'l', 'a', 'n', 'g'}
    x:=arr[0:len(arr)]//也就是x:=arr[0:6]
    for i:=0;i<len(x);i++{
         fmt.Printf("%c",x[i])   
    }
}
//output:golang
复制代码

5、用make()创建切片 当make()接受两个参数时:

var slice []int = make([]int,10)//slice := make([]int ,10)
//这里的10就是len,是数组的长度也是切片的初始长度
复制代码

当make()接受三个参数时:

slice := maek([]int,10,20)
//20是整个数组的长度,切片只占了一部分
//等同于:slice := new([20]int)[0:10]
复制代码

6、for-range结构 先写一个for循环结构进行类比:

for(int i=0;i<strlen(arr);i++){
	printf("arr[%d] is %d",i,a[i]);
复制代码

再写出for-range循环: 其中idex就是对i循环,value也就是这个索引位置的值arr[i].

//一般写法
for idex,value := range slice {
	...(循环内的具体语句)eg.fmt.Printf("arr[%d] is %d",idex,value)
}
//如果只需要值
for _,value := range slice {
	...(循环内的具体语句)eg.fmt.Printf("%d",value)
}
//如果只需要索引
for idex := range slice {
	...(循环内的具体语句)eg.fmt.Printf("It`s posion is %d",idex)
}
复制代码

7、切片重组(reslice) 改变切片长度的过程称之为切片重组 reslicing 可以用循环结构将切片长度为0的切片slice逐渐填充为长度为总容量cap的切片reslice 搬运一个实例过来:

package main
import "fmt"
func main() {
	slice1 := make([]int, 0, 10)
	// load the slice, cap(slice1) is 10:
	for i := 0; i < cap(slice1); i++ {
		slice1 = slice1[0:i+1]
		slice1[i] = i
		fmt.Printf("The length of slice is %d\n", len(slice1))
	}

	// print the slice:
	for i := 0; i < len(slice1); i++ {
		fmt.Printf("Slice at %d is %d\n", i, slice1[i])
	}
}
复制代码

8、切片的复制与追加

package main
import "fmt"

func main() {
    sliceFrom := []int{1, 2, 3}
    sliceTo := make([]int, 10)
    
    n := copy(sliceTo, sliceFrom)
    fmt.Println(sliceTo)
    fmt.Printf("Copied %d elements\n", n) // n == 3
    
    slice := []int{1, 2, 3}
    slice = append(slice, 4, 5, 6)
    fmt.Println(slice)
    }
复制代码

9、map类型的声明 初始化

var map1 map[string]int
map1 = map[string]int{"one":1,"two":0}
map1["three"]=3
map1["ten"]=10
//合并写法
map2 := map[string]int{
	"one":1,"two":2}
//用make()声明map类型
map3 := make(map[string]int)
复制代码

10、测试map中键值对是否存在

package main
import "fmt"

func main() {
	var val int
	var isPresent bool
	map1 := make(map[string]int)
	map1["one"]=1
	map1["two"]=2
	val,isPresent = map1["two"]//如不需要取值,用_代替即可
	if isPresent{
		fmt.Printf("%v!the value of two is %d",isPresent,val)
	}else{
		fmt.Printf("%v!map1 does not contain two",isPresent)
	}
} 
//output:true!the value of two is 2
复制代码

11、元素的删除

//前面的代码同上,如下用delete()函数操作
	delete(map1,"one")
	val,isPresent = map1["one"]
	if isPresent{
		fmt.Printf("%v!the value of one is %d\n",isPresent,val)
	}else{
		fmt.Printf("%v!map1 does not contain one\n",isPresent)
	}
//output:false!map1 does not contain one
复制代码

12、for-range处理map

package main
import "fmt"

func main() {
	map1 := make(map[string]int)
	map1["Mon"]=1
	map1["Tue"]=2
	map1["Wed"]=3
	map1["Thu"]=4
	map1["Fri"]=5
	map1["Sat"]=6
	map1["Sun"]=7
	for key,val := range map1{
		fmt.Printf("%s is the %d of a week\n",key,val)
	}
} 
//注意:map类型默认为无序排列的!
/*output:
Fri is the 5 of a week
Sat is the 6 of a week
Sun is the 7 of a week
Mon is the 1 of a week
Tue is the 2 of a week
Wed is the 3 of a week
Thu is the 4 of a week*/
复制代码

13、map类型的切片

package main
import "fmt"

func main() {
	items := make([]map[int]int, 5)
	for i:= range items {
		items[i] = make(map[int]int, 1)
		items[i][1] = 2
	}
	fmt.Printf("Version A: Value of items: %v\n", items)
//注意区分:make(map[int][]int)这个是用切片作为map的值,用于一个key对应多个value
复制代码

14、map的排序 首先将key/value拷贝进一个切片,对切片调用sort包进行排序 教程中采用的是map[string]int类型,将string进行字母排序后输出即可 我们思考一下:如果是对int进行排序呢?我们将int赋值给一个切片value 以一个星期每天为例:

//拷贝到切片后排序结果
value[0]=1
value[1]=2
value[2]=3
......
//但是将int排序后很难再去map中找其对应的string
复制代码

于是再循环一次map,判断哪个string对应按顺序排列的int

package main
import "fmt"
import "sort"

func main() {
	map1 := make(map[string]int)
	map1["Mon"]=1
	map1["Tue"]=2
	map1["Wed"]=3
	map1["Thu"]=4
	map1["Fri"]=5
	map1["Sat"]=6
	map1["Sun"]=7
	fmt.Println("unsorted:")
	for key,val := range map1{
		fmt.Printf("%s is the %d of a week\n",key,val)
	}
	fmt.Println("sorted:")
	value := make([]int,len(map1))
	i := 0
	for _,val := range map1{
		value[i]=val
		i++
	}
	sort.Ints(value)
	for i,_ := range value{
		for j := range map1{
			if map1[j]== value[i]{
				fmt.Printf("%s is the %d of a week\n",j,value[i])			
			}
		}
	}
} 
复制代码

output:

unsorted:
Wed is the 3 of a week
Thu is the 4 of a week
Fri is the 5 of a week
Sat is the 6 of a week
Sun is the 7 of a week
Mon is the 1 of a week
Tue is the 2 of a week
sorted:
Mon is the 1 of a week
Tue is the 2 of a week
Wed is the 3 of a week
Thu is the 4 of a week
Fri is the 5 of a week
Sat is the 6 of a week
Sun is the 7 of a week
复制代码

15、map的键值对调

package main
import "fmt"

func main() {
	map1 := make(map[string]int)
	map1["Mon"]=1
	map1["Tue"]=2
	map1["Wed"]=3
	map1["Thu"]=4
	map1["Fri"]=5
	map1["Sat"]=6
	map1["Sun"]=7
	invMap := make(map[int]string,len(map1))
	for k,v := range map1{
		invMap[v]=k
	}
	fmt.Println("inverted:")
	for k,v := range invMap{
		fmt.Printf("The %d day is %s\n",k,v)
	}
} 
复制代码

output:

inverted:
The 4 day is Thu
The 5 day is Fri
The 6 day is Sat
The 7 day is Sun
The 1 day is Mon
The 2 day is Tue
The 3 day is Wed
复制代码

当然这个时候发现,我们再用map排序方法对数字进行排序,输出对应字符串也就非常方便了!

文章分类
后端
文章标签