github.com/spotify/syslog-redirector-golang@v0.0.0-20140320174030-4859f03d829a/blog/content/slices/prog130.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 // Append appends the items to the slice. 27 // First version: just loop calling Extend. 28 func Append(slice []int, items ...int) []int { 29 for _, item := range items { 30 slice = Extend(slice, item) 31 } 32 return slice 33 } 34 35 func main() { 36 // START OMIT 37 slice1 := []int{0, 1, 2, 3, 4} 38 slice2 := []int{55, 66, 77} 39 fmt.Println(slice1) 40 slice1 = Append(slice1, slice2...) // The '...' is essential! 41 fmt.Println(slice1) 42 // END OMIT 43 }