github.com/rohankumardubey/syslog-redirector-golang@v0.0.0-20140320174030-4859f03d829a/blog/content/slices/prog140.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 // Append appends the elements to the slice. 12 // Efficient version. 13 func Append(slice []int, elements ...int) []int { 14 n := len(slice) 15 total := len(slice) + len(elements) 16 if total > cap(slice) { 17 // Reallocate. Grow to 1.5 times the new size, so we can still grow. 18 newSize := total*3/2 + 1 19 newSlice := make([]int, total, newSize) 20 copy(newSlice, slice) 21 slice = newSlice 22 } 23 slice = slice[:total] 24 copy(slice[n:], elements) 25 return slice 26 } 27 28 func main() { 29 // START OMIT 30 slice1 := []int{0, 1, 2, 3, 4} 31 slice2 := []int{55, 66, 77} 32 fmt.Println(slice1) 33 slice1 = Append(slice1, slice2...) // The '...' is essential! 34 fmt.Println(slice1) 35 // END OMIT 36 }