github.com/graybobo/golang.org-package-offline-cache@v0.0.0-20200626051047-6608995c132f/x/blog/content/slices/prog110.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 // Extend extends the slice by adding the element to the end. 14 func Extend(slice []int, element int) []int { 15 n := len(slice) 16 if n == cap(slice) { 17 // Slice is full; must grow. 18 // We double its size and add 1, so if the size is zero we still grow. 19 newSlice := make([]int, len(slice), 2*len(slice)+1) 20 copy(newSlice, slice) 21 slice = newSlice 22 } 23 slice = slice[0 : n+1] 24 slice[n] = element 25 return slice 26 } 27 28 func main() { 29 // START OMIT 30 slice := make([]int, 0, 5) 31 for i := 0; i < 10; i++ { 32 slice = Extend(slice, i) 33 fmt.Printf("len=%d cap=%d slice=%v\n", len(slice), cap(slice), slice) 34 fmt.Println("address of 0th element:", &slice[0]) 35 } 36 // END OMIT 37 }