[Go] Slices vs Array

Posted answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Go] Slices vs Array相关的知识,希望对你有一定的参考价值。

It is recommended to use ‘slice‘ over ‘Array‘. 

An array variable denotes the entire array; it is not a pointer to the first array element (as would be the case in C). This means that when you assign or pass around an array value you will make a copy of its contents.

Arrays have their place, but they‘re a bit inflexible, so you don‘t see them too often in Go code. Slices, though, are everywhere. They build on arrays to provide great power and convenience.

letters := []string{"a", "b", "c", "d"}

You can call built-in function:

var s []byte
s = make([]byte, 5, 5)
// s == []byte{0, 0, 0, 0, 0}

When you modifiy the slices, it pass around the reference:

d := []byte{‘r‘, ‘o‘, ‘a‘, ‘d‘}
e := d[2:] 
// e == []byte{‘a‘, ‘d‘}
e[1] = ‘m‘
// e == []byte{‘a‘, ‘m‘}
// d == []byte{‘r‘, ‘o‘, ‘a‘, ‘m‘}

 

More information: https://blog.golang.org/go-slices-usage-and-internals

 

以上是关于[Go] Slices vs Array的主要内容,如果未能解决你的问题,请参考以下文章

17 Go Slices: usage and internals

Go Slices:用法和内部结构

golang golang_array_slices_maps

Go 语言入门很简单 -- 7. Go Slices #私藏项目实操分享#

go内建函数(记录)

2.5 Go语言中的切片(Slice)