github.com/spotify/syslog-redirector-golang@v0.0.0-20140320174030-4859f03d829a/blog/content/slices/prog100.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 // Insert inserts the value into the slice at the specified index, 12 // which must be in range. 13 // The slice must have room for the new element. 14 func Insert(slice []int, index, value int) []int { 15 // Grow the slice by one element. 16 slice = slice[0 : len(slice)+1] 17 // Use copy to move the upper part of the slice out of the way and open a hole. 18 copy(slice[index+1:], slice[index:]) 19 // Store the new value. 20 slice[index] = value 21 // Return the result. 22 return slice 23 } 24 25 func main() { 26 slice := make([]int, 10, 20) // Note capacity > length: room to add element. 27 for i := range slice { 28 slice[i] = i 29 } 30 fmt.Println(slice) 31 slice = Insert(slice, 5, 99) 32 fmt.Println(slice) 33 // OMIT 34 }