Vector

Go originally had a vector implementation, but this was removed very early on in the language development (October 11, 2011). It was deemed that slices are better (as was the title of the pull request) and slices became the de facto vector implementation in Go. We can implement a slice as follows:

sliceExample := []string{"slices", "are", "cool", "in", "go"}

Slices are beneficial because, like vectors in the STL, they can grow or shrink based on addition or deletion. In our example, we create a slice, append a value to the slice, and remove a value from the slice, as illustrated in the following code:

package main

import "fmt"

// Remove i indexed item in slice
func remove(s []string, i int) []string {
copy(s[i:], s[i+1:])
return s[:len(s)-1]
}

func main() {
slice := []string{"foo", "bar", "baz"} // create a slice
slice = append(slice, "tri") // append a slice
fmt.Println("Appended Slice: ", slice) // print slice [foo, bar baz, tri]
slice = remove(slice, 2) // remove slice item #2 (baz)
fmt.Println("After Removed Item: ", slice) // print slice [foo, bar, tri]
}

As we execute our vector example, we can see our appending and removing in action, as shown in the following screenshot:

We can see that the tri element was appended to the end of our slice, and we can also see that the baz element (element number 3 in the slice) was removed based on our remove() function call.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.219.182.76