golang中的数组是value type而不是reference type ,也就是说,进行数组间的相互赋值时,使用的不是同一个内存空间,开辟了另一个内存空间用以存放新的数组,所以改变新的数组中元素并不会改变原数组的值,也就是说,使用的是深复制。
所以数组作为参数进行传递时,也是按值传递,不会改变原数组的元素。
funcchangeLocal(num [5]int) { num[0] =55 fmt.Println("inside function ", num)}funcmain() { num := [...]int{5, 6, 7, 8, 8} fmt.Println("before passing to function ", num)changeLocal(num) //num is passed by value fmt.Println("after passing to function ", num)}
a := [5]int{1, 2, 67, 76, 88}var b []int= a[1:4]// 1, 2, 67a := [5]int{76, 77, 78, 79, 80}var b = a[1:4] //creates a slice from a[1] to a[3]fmt.Println(b[1:4], b) // 注意此处slice的len为3,cap为4,不可以用[]访问,但是可以使用[:]格式进行访问,
numa := [3]int{78, 79 ,80} nums1 := numa[:] //creates a slice which contains all elements of the array nums2 := numa[:] fmt.Println("array before change 1",numa) nums1[0] =100 fmt.Println("array after modification to slice nums1", numa) nums2[1] =101 fmt.Println("array after modification to slice nums2", numa)
funcappend([]T, x ...T) []T// 用于动态扩充一个切片,参数x ...T表示接受多个类型为T的值作为参数,可变长参数// 当一个切片进行扩充时,如果长度与容量相等,表示空间已经用完// 此时建立一个底层新的数组,容量为原来2倍并且把原数组的数据copy到新的数组中去,形成新的底层数组// 并且把新数组的引用赋给切片
cars := []string{"Ferrari", "Honda", "Ford"}fmt.Println("cars:", cars, "has old length", len(cars), "and capacity",cap(cars)) //capacity of cars is 3cars =append(cars, "Toyota")fmt.Println("cars:", cars, "has new length", len(cars), "and capacity",cap(cars)) //capacity of cars is doubled to 6