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