商君

导航

Go Example--切片

package main

import (
	"fmt"
)

func main()  {
	//make来初始化一个切片,必须指名切片的长度
	s:= make([]string, 3)
	fmt.Println("emp:",s)

	s[0] = "a"
	s[1] = "b"
	s[2] = "c"
	fmt.Println("set:",s)
	fmt.Println("get:",s[2])
	fmt.Println("len:",len(s))

	//append函数向切片尾部添加值,切片长度不够时,会重新申请内存给s
	s = append(s, "d")
	s = append(s,"e","f")
	fmt.Println("apd:",s)

	c:=make([]string,len(s))
	//copy是在内存中复制s到c
	copy(c,s)
	fmt.Println("cpy:",c)

	//l和s均指向相同的底层数组
	l:=s[2:5]
	fmt.Println("sl1:",l)

	l=s[:5]
	fmt.Println("sl1:",l)
	l=s[2:]
	fmt.Println("sl1:",l)

	t:=[]string{"g","h","i"}
	fmt.Println("dcl:",t)

	//二维切片,
	twoD := make([][]int,3)
	for i:=0; i<3;i++  {
		innerLen := i+1;
		//内部需要重新申请内存
		twoD[i] = make([]int,innerLen)
		for j:=0;j<innerLen ;j++  {
			twoD[i][j] =i+j
		}
	}
	fmt.Println("2d: ",twoD)
}

posted on 2018-10-15 14:33  漫步者01  阅读(78)  评论(0编辑  收藏  举报