How to Shuffle A Slice or Array in Go (Golang)

Go (Golang) offers a vast standard library which contains almost anything you need, without the necessity to import external pacakges. When shuffling a slice (or array) in Go this is also the case where we have a ready-to-use function that allows us to swap elements randomly within a slice in Go (Golang). The function is rand.Shuffle

func Shuffle(n int, swap func(i, j int))

Here’s the definition directly from the official website

Shuffle pseudo-randomizes the order of elements using the default Source. n is the number of elements. Shuffle panics if n < 0. swap swaps the elements with indexes i and j.

Let’s have a look at an example to undersand how it can be used

You might need to initialise the random generator with rand.Seed so that you won’t get always the same result

package main

import (

func main() {
    alphabet := []string{"a", "b", "c", "d", "e", "f", "g", "h"}
    rand.Shuffle(len(alphabet), func(i, j int) {
        alphabet[i], alphabet[j] = alphabet[j], alphabet[i]

You can also run the code from within the Go Playground (Remember that the Go Playground is a sandbox and has a fixed time so the result will always be the same!)

Here’s how the output could look like when running the above code snippet

$ go run shuffle.go
[h d a c e b g f]
Join the Golang Developers Community on Golang Cafe