github.com/spotify/syslog-redirector-golang@v0.0.0-20140320174030-4859f03d829a/blog/content/slices/prog110.go (about) 1 // Copyright 2013 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package main 6 7 import ( 8 "fmt" 9 ) 10 11 // Extend extends the slice by adding the element to the end. 12 func Extend(slice []int, element int) []int { 13 n := len(slice) 14 if n == cap(slice) { 15 // Slice is full; must grow. 16 // We double its size and add 1, so if the size is zero we still grow. 17 newSlice := make([]int, len(slice), 2*len(slice)+1) 18 copy(newSlice, slice) 19 slice = newSlice 20 } 21 slice = slice[0 : n+1] 22 slice[n] = element 23 return slice 24 } 25 26 func main() { 27 // START OMIT 28 slice := make([]int, 0, 5) 29 for i := 0; i < 10; i++ { 30 slice = Extend(slice, i) 31 fmt.Printf("len=%d cap=%d slice=%v\n", len(slice), cap(slice), slice) 32 fmt.Println("address of 0th element:", &slice[0]) 33 } 34 // END OMIT 35 }