rocket9labs.com/content/post/gotcha-slice-append-backing...

32 lines
753 B
Markdown
Raw Normal View History

2019-09-27 04:48:49 +00:00
---
2019-11-20 12:48:44 +00:00
title: "Gotcha - Up-ending a backing array"
2019-09-27 04:48:49 +00:00
date: 2019-09-26T21:42:18-07:00
categories: [gotcha]
2019-11-20 12:48:44 +00:00
draft: true
2019-09-27 04:48:49 +00:00
---
2019-11-20 12:48:44 +00:00
To give better context to the problem being presented in this article, we must go over how slices work.
A slice value consists of three parts: a pointer to a backing array, a length and a capacity.
Excerpt of **runtime/slice.go** from the standard library:
```go
type slice struct {
array unsafe.Pointer
len int
cap int
}
```
When calling append on a slice whose length is the same as its capacity, a new backing array of greater size is created. The previous backing array's contents are copied.
A range of elements from a slice may be selected like so:
```go
bar := foo[4:7]
```
When calling append on such a slice,