惜风不起、唯有努力!
golang 中的切片

golang 中的切片

//定义切片
var qps  = []string{"tom","alix","xff","heeys"}

//声明并初始化一个切片
var qps []int   //声明一维切片
qps = make([]int,2,6)  //初始化,2是切片长度, 6是切片容量

//增
qps = append(qps, 100)
qps = append(qps, 200)
qps = append(qps, 300)

//删
qps = qps[2:]

//改

package main

import "fmt"

func qiep(){
	//二维切片
	qp := [][]int{
		{1,67},
		{3,4,7},
	}
	fmt.Println(len(qp))
	fmt.Println(len(qp[0]),cap(qp[1]))
	fmt.Println(len(qp[1]),cap(qp[1]))

	var qps []int   //声明一维切片
	qps = make([]int,2,6)  //初始化
	fmt.Printf("len: %d, cap: %d\n",len(qps),cap(qps))
	fmt.Println(qps)
	qps = append(qps, 100)  //添加值
	qps = append(qps, 100)  //len++
	qps = append(qps, 100)
	qps = append(qps, 100)
	qps = append(qps, 101)
	qps = append(qps, 100)
	qps = append(qps, 100)
	fmt.Println(qps)
	fmt.Printf("len: %d, cap: %d\n",len(qps),cap(qps))
}

func mzqiepian(){
	x := make([]int, 3, 5)  //母切片
	fmt.Println(x)
	a := x[0:2]     //子切片
	a[1] = 9
	fmt.Println(a[1])
	a = append(a, 10)
	a = append(a, 10)
	fmt.Printf("%p, %p\n",&a[0],&x[0])
	fmt.Println(x)
	a = append(a, 10)
	fmt.Printf("%p, %p\n",&a[0],&x[0])
	//内存分离,子变化不影响母
	a = append(a, 10)
	fmt.Printf("%p, %p\n",&a[0],&x[0])  //打印地址
	a[1] = 4
	fmt.Println(a[1])
	fmt.Println(x[1])

}
//函数切片普通传参
//func funcqiepian(x []int){
//	x[0] = 99
//	x[1] = 88
//	x[2] = 77
//}
//
//func funcqiepian1(){
//	a := []int{1,2,3}
//	funcqiepian(a)
//	fmt.Println(a[2])
//}


//函数切片指针传参
func funcqiepian(x *[]int){
	(*x)[0] = 99
	(*x)[1] = 88
	(*x)[2] = 77
}

func funcqiepian2(){
	a := []int{1,2,3}
	funcqiepian(&a)
	fmt.Println(a[2],a[0],a[1])
}

func main() {
	//mzqiepian()
	//funcqiepian1()
	funcqiepian2()
}

发表回复

您的电子邮箱地址不会被公开。