1 前言
切片是动态数组,数组数组是按值赋值,切片是按地址赋值(引用)
2 代码
2.1 数组初始化
func basic_array(){ //var arr2 = [3]int{2,4,6} // 1 //arr2 := [3]int{2,4,6} //2 //var arr2[3]int = [3]int{2,4,6} //3 //var arr2 [3]int //4 //arr2=[3]int{1,3,5} // var arr2 [3]int //5 // var i int // for i=0;i<len(arr2);i++{ // arr2[i] = 10+i; // } // var arr2 [3]int //6 // var arr2 [...]int{1,3,7} //7[...]表示根据元素自适应大小 for i,e := range arr2{ fmt.Println("arr2[",i,"]->",e); } }
2.2 切片初始化
func basic_slice(){ //var arr2 = []int{2,4,6} // 1 //arr2 := []int{2,4,6} //2 //var arr2[]int = [3]int{2,4,6} //3 //var arr2 []int //4 //arr2=[]int{1,3,5} //var slice1 []type = make([]type, len) //5 //slice1 := make([]type, len) //6 //also add parameter capacity //make([]T, length, capacity) //7,8 for i,e := range arr2{ fmt.Println("arr2[",i,"]->",e); } }
3 数组与切片区别
var arr2[3]int = [3]int{2,4,6} var arr1 = arr2 arr1[1]=11 for i,e := range arr1{ fmt.Println("arr1[",i,"]->",e); } for i,e := range arr2{ fmt.Println("arr2[",i,"]->",e); } //result // arr1[ 0 ]-> 2 // arr1[ 1 ]-> 11 // arr1[ 2 ]-> 6 // arr2[ 0 ]-> 2 // arr2[ 1 ]-> 4 // arr2[ 2 ]-> 6 //slice var arr2[]int = []int{2,4,6} var arr1 = arr2 arr1[1]=11 for i,e := range arr1{ fmt.Println("arr1[",i,"]->",e); } for i,e := range arr2{ fmt.Println("arr2[",i,"]->",e); } //result // arr1[ 0 ]-> 2 // arr1[ 1 ]-> 11 // arr1[ 2 ]-> 6 // arr2[ 0 ]-> 2 // arr2[ 1 ]-> 11 // arr2[ 2 ]-> 6