March 2020
Intermediate to advanced
406 pages
8h 39m
English
The reverse algorithm takes a dataset and reverses the values of the set. The Go standard sort package does not have a built-in way to reverse slices. We can write a trivial reverse function in order to reverse the order of our dataset, like so:
package mainimport ( "fmt")func reverse(s []string) []string { for x, y := 0, len(s)-1; x < y; x, y = x+1, y-1 { s[x], s[y] = s[y], s[x] } return s}func main() { s := []string{"foo", "bar", "baz", "go", "stop"} reversedS := reverse(s) fmt.Println(reversedS)}
This function iterates through the slice, increments and decrements x and y until they converge, and swaps the elements in the slice, as we can see in the following screenshot:
As we can see, our slice is reversed using the reverse() ...
Read now
Unlock full access