go语言中数组与切片的区别

https://blog.csdn.net/Nick_666/article/details/78640870

 

一句话总结:切片是动态数组,注意两者初始化和函数参数的区别

1、初始化:数组需要指定大小,不指定也会根据初始化的自动推算出大小,不可改变

数组: a := […]int{1,2,3} a := [3]int{1,2,3}

切片: a:= []int{1,2,3} a := make([]int, 5) a := make([]int, 5, 10)

//var a […]int = […]int{1, 2, 3} //error
a := […]int{1, 2, 3}
var a2 [3]int = [3]int{4, 5, 6}

切片不需要指定大小

var s []int = []int{1, 2, 3, 4}

2、函数传递:

数组需要明确指定大小,切片不需要。数组是值传递,切片是地址传递

package main
import "fmt"
func changeArray(a [3]int) {
    a[0] = 100
}
func changeSlice(s []int) {
    s[0] = 100
}
func main() {
    //var a [...]int = [...]int{1, 2, 3} //error
    a := [...]int{1, 2, 3}
    changeArray(a)
    fmt.Println(a[0]) //值传递
    var a2 [3]int = [3]int{4, 5, 6}
    a2[2] = 77
    var s []int = []int{1, 2, 3, 4}
    fmt.Println(len(s), cap((s)))
    s = append(s, 6, 7, 8)
    fmt.Println(len(s), cap(s))
    changeSlice(s)
    fmt.Println(s[0]) //地址传递
}

1
4 4
7 8
100
成功: 进程退出代码 0.

Leave a Reply

Your email address will not be published. Required fields are marked *