github.com/graybobo/golang.org-package-offline-cache@v0.0.0-20200626051047-6608995c132f/x/blog/content/slices/prog120.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  // Append appends the items to the slice.
    29  // First version: just loop calling Extend.
    30  func Append(slice []int, items ...int) []int {
    31  	for _, item := range items {
    32  		slice = Extend(slice, item)
    33  	}
    34  	return slice
    35  }
    36  
    37  func main() {
    38  	// START1 OMIT
    39  	slice := []int{0, 1, 2, 3, 4}
    40  	fmt.Println(slice)
    41  	slice = Append(slice, 5, 6, 7, 8)
    42  	fmt.Println(slice)
    43  	// END1 OMIT
    44  }