Welcome To Golang By Example

Menu
  • Home
  • Blog
Menu

Pick a random element in an array or slice in Go (Golang)

Posted on March 31, 2023March 31, 2023 by admin

Table of Contents

  • Overview
  • Code

Overview

‘mat/rand’ package of golang contains a Intn function that can be used to generate a pseudo-random number between [0,n). Bracket at the end means that n is exclusive. This function can be utilized to pick a random element in an array or slice of int or string.

To know more about what pseudo-random number means, checkout this post – /generate-random-number-golang

Below is the signature of this method. It takes input a number n and will return a number x in range 0<=x<n.

func Intn(n int) int

Code

We can directly index an element in a slice of int. See below program for picking up random from a slice of int.

package main
import (
"fmt"
"math/rand"
)
func main() {
in := []int{2, 5, 6}
randomIndex := rand.Intn(len(in))
pick := in[randomIndex]
fmt.Println(pick)
}

Output:

Between 2, 5 or 6
  • array
  • go
  • golang
  • pick
  • slice
  • Popular Articles

    Golang Comprehensive Tutorial Series

    All Design Patterns in Go (Golang)

    Slice in golang

    Variables in Go (Golang) – Complete Guide

    OOP: Inheritance in GOLANG complete guide

    Using Context Package in GO (Golang) – Complete Guide

    All data types in Golang with examples

    Understanding time and date in Go (Golang) – Complete Guide

    ©2023 Welcome To Golang By Example | Design: Web XP