Data Structure and Algorithm My Go Tutorial

Slice, for, len(), cap(), append, copy

Shortcoming of Go array is address by Go slice. It can be appended to elements after the capacity has reached its size. Slices are dynamic and can double the current capacity in order to add more elements.

var slice = []int{1,3,5,6}
fmt.Println("Capacity", cap(slice))
fmt.Println("Length", len(slice))
slice = append(slice, 8)
fmt.Println(“Capacity”, cap(slice))
fmt.Println(“Length”, len(slice))

Slice and Functions ( call by reference)

package main

import "fmt"

//twiceValue method given slice of int type
func twiceValue(slice []int) {
	for i, value := range slice {
		slice[i] = 2 * value

func main() {
	var slice = []int{1, 3, 5, 6}
	// pass by reference when twiceValue function called

	for i := 0; i < len(slice); i++ {
		// Original slice value modified by twiceValue function
		fmt.Println("new slice value", slice[i])