17 Go Slices: usage and internals GO语言切片: 使用和内部
Go Slices: usage and internals GO语言切片: 使用和内部
5 January 2011
Introduction
Go's slice type provides a convenient and efficient means of working with sequences of typed data. Slices are analogous to arrays in other languages, but have some unusual properties. This article will look at what slices are and how they are used.
Arrays
The slice type is an abstraction built on top of Go's array type, and so to understand slices we must first understand arrays.
An array type definition specifies a length and an element type. For example, the type [4]int represents an array of four integers. An array's size is fixed; its length is part of its type ([4]int and [5]int are distinct, incompatible types). Arrays can be indexed in the usual way, so the expression s[n] accesses the nth element, starting from zero.
var a [4]int
a[0] = 1
i := a[0]
// i == 1
Arrays do not need to be initialized explicitly; the zero value of an array is a ready-to-use array whose elements are themselves zeroed:
// a[2] == 0, the zero value of the int type
The in-memory representation of [4]int is just four integer values laid out sequentially:

Go's arrays are values. 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. (To avoid the copy you could pass a pointer to the array, but then that's a pointer to an array, not an array.) One way to think about arrays is as a sort of struct but with indexed rather than named fields: a fixed-size composite value.
An array literal can be specified like so:
b := [2]string{"Penn", "Teller"}
Or, you can have the compiler count the array elements for you:
b := [...]string{"Penn", "Teller"}
In both cases, the type of b is [2]string.
Slices
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.
The type specification for a slice is []T, where T is the type of the elements of the slice. Unlike an array type, a slice type has no specified length.
A slice literal is declared just like an array literal, except you leave out the element count:
letters := []string{"a", "b", "c", "d"}
A slice can be created with the built-in function called make, which has the signature,
func make([]T, len, cap) []T
where T stands for the element type of the slice to be created. The make function takes a type, a length, and an optional capacity. When called, make allocates an array and returns a slice that refers to that array.
var s []byte
s = make([]byte, 5, 5)
// s == []byte{0, 0, 0, 0, 0}
When the capacity argument is omitted, it defaults to the specified length. Here's a more succinct version of the same code:
s := make([]byte, 5)
The length and capacity of a slice can be inspected using the built-in len and cap functions.
len(s) == 5
cap(s) == 5
The next two sections discuss the relationship between length and capacity.
The zero value of a slice is nil. The len and cap functions will both return 0 for a nil slice.
A slice can also be formed by "slicing" an existing slice or array. Slicing is done by specifying a half-open range with two indices separated by a colon. For example, the expression b[1:4] creates a slice including elements 1 through 3 of b (the indices of the resulting slice will be 0 through 2).
b := []byte{'g', 'o', 'l', 'a', 'n', 'g'}
// b[1:4] == []byte{'o', 'l', 'a'}, sharing the same storage as b
The start and end indices of a slice expression are optional; they default to zero and the slice's length respectively:
// b[:2] == []byte{'g', 'o'}
// b[2:] == []byte{'l', 'a', 'n', 'g'}
// b[:] == b
This is also the syntax to create a slice given an array:
x := [3]string{"Лайка", "Белка", "Стрелка"}
s := x[:] // a slice referencing the storage of x
Slice internals
A slice is a descriptor of an array segment. It consists of a pointer to the array, the length of the segment, and its capacity (the maximum length of the segment).

Our variable s, created earlier by make([]byte, 5), is structured like this:

The length is the number of elements referred to by the slice. The capacity is the number of elements in the underlying array (beginning at the element referred to by the slice pointer). The distinction between length and capacity will be made clear as we walk through the next few examples.
As we slice s, observe the changes in the slice data structure and their relation to the underlying array:
s = s[2:4]

Slicing does not copy the slice's data. It creates a new slice value that points to the original array. This makes slice operations as efficient as manipulating array indices. Therefore, modifying the elements (not the slice itself) of a re-slice modifies the elements of the original slice:
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'}
Earlier we sliced s to a length shorter than its capacity. We can grow s to its capacity by slicing it again:
s = s[:cap(s)]

A slice cannot be grown beyond its capacity. Attempting to do so will cause a runtime panic, just as when indexing outside the bounds of a slice or array. Similarly, slices cannot be re-sliced below zero to access earlier elements in the array.
Growing slices (the copy and append functions)
To increase the capacity of a slice one must create a new, larger slice and copy the contents of the original slice into it. This technique is how dynamic array implementations from other languages work behind the scenes. The next example doubles the capacity of s by making a new slice, t, copying the contents of s into t, and then assigning the slice value t to s:
t := make([]byte, len(s), (cap(s)+1)*2) // +1 in case cap(s) == 0
for i := range s {
t[i] = s[i]
}
s = t
The looping piece of this common operation is made easier by the built-in copy function. As the name suggests, copy copies data from a source slice to a destination slice. It returns the number of elements copied.
func copy(dst, src []T) int
The copy function supports copying between slices of different lengths (it will copy only up to the smaller number of elements). In addition, copy can handle source and destination slices that share the same underlying array, handling overlapping slices correctly.
Using copy, we can simplify the code snippet above:
t := make([]byte, len(s), (cap(s)+1)*2)
copy(t, s)
s = t
A common operation is to append data to the end of a slice. This function appends byte elements to a slice of bytes, growing the slice if necessary, and returns the updated slice value:
func AppendByte(slice []byte, data ...byte) []byte {
m := len(slice)
n := m + len(data)
if n > cap(slice) { // if necessary, reallocate
// allocate double what's needed, for future growth.
newSlice := make([]byte, (n+1)*2)
copy(newSlice, slice)
slice = newSlice
}
slice = slice[0:n]
copy(slice[m:n], data)
return slice
}
One could use AppendByte like this:
p := []byte{2, 3, 5}
p = AppendByte(p, 7, 11, 13)
// p == []byte{2, 3, 5, 7, 11, 13}
Functions like AppendByte are useful because they offer complete control over the way the slice is grown. Depending on the characteristics of the program, it may be desirable to allocate in smaller or larger chunks, or to put a ceiling on the size of a reallocation.
But most programs don't need complete control, so Go provides a built-in append function that's good for most purposes; it has the signature
func append(s []T, x ...T) []T
The append function appends the elements x to the end of the slice s, and grows the slice if a greater capacity is needed.
a := make([]int, 1)
// a == []int{0}
a = append(a, 1, 2, 3)
// a == []int{0, 1, 2, 3}
To append one slice to another, use ... to expand the second argument to a list of arguments.
a := []string{"John", "Paul"}
b := []string{"George", "Ringo", "Pete"}
a = append(a, b...) // equivalent to "append(a, b[0], b[1], b[2])"
// a == []string{"John", "Paul", "George", "Ringo", "Pete"}
Since the zero value of a slice (nil) acts like a zero-length slice, you can declare a slice variable and then append to it in a loop:
// Filter returns a new slice holding only
// the elements of s that satisfy fn()
func Filter(s []int, fn func(int) bool) []int {
var p []int // == nil
for _, v := range s {
if fn(v) {
p = append(p, v)
}
}
return p
}
A possible "gotcha"
As mentioned earlier, re-slicing a slice doesn't make a copy of the underlying array. The full array will be kept in memory until it is no longer referenced. Occasionally this can cause the program to hold all the data in memory when only a small piece of it is needed.
For example, this FindDigits function loads a file into memory and searches it for the first group of consecutive numeric digits, returning them as a new slice.
var digitRegexp = regexp.MustCompile("[0-9]+")
func FindDigits(filename string) []byte {
b, _ := ioutil.ReadFile(filename)
return digitRegexp.Find(b)
}
This code behaves as advertised, but the returned []byte points into an array containing the entire file. Since the slice references the original array, as long as the slice is kept around the garbage collector can't release the array; the few useful bytes of the file keep the entire contents in memory.
To fix this problem one can copy the interesting data to a new slice before returning it:
func CopyDigits(filename string) []byte {
b, _ := ioutil.ReadFile(filename)
b = digitRegexp.Find(b)
c := make([]byte, len(b))
copy(c, b)
return c
}
A more concise version of this function could be constructed by using append. This is left as an exercise for the reader.
Further Reading
Effective Go contains an in-depth treatment of slices and arrays, and the Go language specification defines slices and their associated helper functions.
By Andrew Gerrand
Related articles
- HTTP/2 Server Push
- Introducing HTTP Tracing
- Generating code
- Arrays, slices (and strings): The mechanics of 'append'
- Introducing the Go Race Detector
- Go maps in action
- go fmt your code
- Organizing Go code
- Debugging Go programs with the GNU Debugger
- The Go image/draw package
- The Go image package
- The Laws of Reflection
- Error handling and Go
- "First Class Functions in Go"
- Profiling Go Programs
- A GIF decoder: an exercise in Go interfaces
- Introducing Gofix
- Godoc: documenting Go code
- Gobs of data
- C? Go? Cgo!
- JSON and Go
- Go Concurrency Patterns: Timing out, moving on
- Defer, Panic, and Recover
- Share Memory By Communicating
- JSON-RPC: a tale of interfaces
17 Go Slices: usage and internals GO语言切片: 使用和内部的更多相关文章
- Go Slices: usage and internals
Introduction Go's slice type provides a convenient and efficient means of working with sequences of ...
- Go 语言切片(Slice)
Go 语言切片是对数组的抽象. Go 数组的长度不可改变,在特定场景中这样的集合就不太适用,Go中提供了一种灵活,功能强悍的内置类型切片("动态数组"),与数组相比切片的长度是不固 ...
- C++语言编译系统提供的内部数据类型的自动隐式转换
C++语言编译系统提供的内部数据类型的自动隐式转换规则如下: 程序在执行算术运算时,低类型自动隐式转换为高类型. 在函数调用时,将实参值赋给形参,系统隐式的将实参转换为形参的类型,并赋值给形参. 函数 ...
- Go语言切片
切片 Go 语言切片相当于是对数组的抽象. 由于Go 数组的长度不可改变,在特定场景中这样的集合就不太适用,Go中提供了一种灵活,功能强悍的内置类型切片("动态数组"),与数组相比 ...
- Go 语言 切片的使用(增删改查)
Go 语言 切片的使用(增删改查) 引言Golang 的数组是固定长度,可以容纳相同数据类型的元素的集合.但是当长度固定了,在使用的时候肯定是会带来一些限制,比如说:申请的长度太大会浪费内存,太小又不 ...
- go语言切片切片与指针
go语言 1.切片的定义 切片不是真正意义上的动态数组,是引用类型. var arraySlice []int
- Go语言 ( 切片)
本文主要介绍Go语言中切片(slice)及它的基本使用. 引子 因为数组的长度是固定的并且数组长度属于类型的一部分,所以数组有很多的局限性. 例如: func arraySum(x []int) in ...
- Go语言中数组的内部实现和基础功能
数组的内部实现和基础功能 因为数组是切片和映射的基础数据结构.理解了数组的工作原理,有助于理解切片和映射提供的优雅和强大的功能. 内部实现 在Go语言里,数组是一个长度固定的数据类型,用于存储一段具有 ...
- 【C语言】C语言外部变量和内部变量
目录: [外部变量] · 定义 · 用extern修饰变量 [内部变量] · 定义 · 用static修饰变量 1.外部变量 · 定义 定义的变量能被本文件和其它文件访问的变量,称为外部变量. 注: ...
随机推荐
- BZOJ2789 [Poi2012]Letters 【树状数组】
题目链接 BZOJ 题解 如果我们给\(A\)中所有字母按顺序编号,给\(B\)中所有字母编上相同的号码 对于\(B\)中同一种,显然号码应该升序 然后求逆序对即可 #include<algor ...
- java多线程 -- ForkJoinPool 分支/ 合并框架 工作窃取
Fork/Join 框架:就是在必要的情况下,将一个大任务,进行拆分(fork)成若干个小任务(拆到不可再拆时),再将一个个的小任务运算的结果进行 join 汇总. Fork/Join 框架与线程池的 ...
- window10+Anaconda3-4.2+python3.5+Pycharm+清华镜像源安装
window下对python3.5适用性比较好,Anaconda4.2里面包含了python3.5. https://mirrors.tuna.tsinghua.edu.cn/anaconda/arc ...
- WEB下面路径的问题
web 中的 / 到底代表什么? 绝对路径-以Web站点根目录为参考基础的目录路径.之所以称为绝对,意指当所有网页引用同一个文件时,所使用的路径都是一样的.相对路径-以引用文件之网页所在位置为参考 ...
- 【Asp.net入门15】第一个Asp.net应用程序-输入验证
前言 所谓输入验证,顾名思义就是验证用户输入符不符合要求.前面我们已经完成了这个简单的应用程序,但还有一个问题需要解决:用户可以在Default.aspx窗体中 提交任何数据,甚至可以提交根本不包含任 ...
- np.diff函数
np.diff函数 觉得有用的话,欢迎一起讨论相互学习~Follow Me 数组中a[n]-a[n-1] import numpy as np a=np.array([1, 6, 7, 8, 12]) ...
- 科学计算三维可视化---Mayavi入门(Mayavi库的基本元素和绘图实例)
一:Mayavi库的基本元素 .处理图形可视化和图形操作的mlab模块 .操作管线对象,窗口对象的api (一)mlab模块 (二)mayavi的api 二:快速绘图实例 (一)mlab.mesh的使 ...
- python---requests和beautifulsoup4模块的使用
Requests:是使用 Apache2 Licensed 许可证的 基于Python开发的HTTP 库,其在Python内置模块的基础上进行了高度的封装,从而使得Pythoner进行网络请求时,变得 ...
- VS项目属性的一些配置项的总结(important)
以下内容为“原创”+“转载” 首先,解决方案和项目文件夹包含关系(c++项目): VS解决方案和各个项目文件夹以及解决方案和各个项目对应的配置文件包含关系,假设新建一个项目ssyy,解决方案起名fan ...
- bzoj千题计划109:bzoj1019: [SHOI2008]汉诺塔
http://www.lydsy.com/JudgeOnline/problem.php?id=1019 题目中问步骤数,没说最少 可以大胆猜测移动方案唯一 (真的是唯一但不会证) 设f[i][j] ...