Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Slice 声明和初始化 #3

Open
kevinyan815 opened this issue Aug 1, 2019 · 0 comments
Open

Slice 声明和初始化 #3

kevinyan815 opened this issue Aug 1, 2019 · 0 comments

Comments

@kevinyan815
Copy link
Owner

kevinyan815 commented Aug 1, 2019

在Go中一个数组的长度是固定的,但是切片的长度是可以动态扩充的,所以在实际应用中切片比数组更常用。

An array has a fixed size. A slice, on the other hand, is a dynamically-sized, flexible view into the elements of an array. In practice, slices are much more common than arrays.

声明切片

var identifier []type

切片在未初始化前默认的zero value是nil, 长度是0.

初始化切片

  • 从已知数组初始化切片
    var slice1 []type = array1[start:end]
    表示 slice1 是由数组 arr1 从 start 索引到 end-1 索引之间的元素构成的子集(切分数组,start:end 被称为 slice 表达式)

  • 初始化相关数组和切片
    var x = []int{2, 3, 5, 7, 11}这样就创建了一个长度为 5 的数组并从这个相关数组创建了一个切片。

  • 用make初始化
    当相关数组还没有定义时,用 make() 函数来创建一个切片 同时创建好相关数组
    make([]type)
    make([]type, len)
    make([]type, len, cap)

引用类型

slice是引用类型,它的零值是nil, 长度是0.

@kevinyan815 kevinyan815 changed the title Slice Slice 声明和初始化 Aug 4, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant