github.com/graybobo/golang.org-package-offline-cache@v0.0.0-20200626051047-6608995c132f/x/blog/content/slices/prog100.go (about) 1 // +build OMIT 2 3 // Copyright 2013 The Go Authors. All rights reserved. 4 // Use of this source code is governed by a BSD-style 5 // license that can be found in the LICENSE file. 6 7 package main 8 9 import ( 10 "fmt" 11 ) 12 13 // Insert inserts the value into the slice at the specified index, 14 // which must be in range. 15 // The slice must have room for the new element. 16 func Insert(slice []int, index, value int) []int { 17 // Grow the slice by one element. 18 slice = slice[0 : len(slice)+1] 19 // Use copy to move the upper part of the slice out of the way and open a hole. 20 copy(slice[index+1:], slice[index:]) 21 // Store the new value. 22 slice[index] = value 23 // Return the result. 24 return slice 25 } 26 27 func main() { 28 slice := make([]int, 10, 20) // Note capacity > length: room to add element. 29 for i := range slice { 30 slice[i] = i 31 } 32 fmt.Println(slice) 33 slice = Insert(slice, 5, 99) 34 fmt.Println(slice) 35 // OMIT 36 }