Welcome To Golang By Example

Menu
  • Home
  • Blog
Menu

Generate a random character in Go (Golang)

Posted on April 2, 2023April 2, 2023 by admin

Table of Contents

  • Overview
  • Code

Overview

‘mat/rand’ package of golang contains an Intn function that can be used to generate a random number between [0,n). The bracket at the end means that n is exclusive.

To know more about what pseudo-random number means, check out 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

The above function can also be used to generate a random character too. See below program, it is used to generate a character. We are also providing a seed value to the rand so that it generates different output. It is used to generate:

  • Random character between lowercase a to z
  • Random character between uppercase A and Z
  • Random character between uppercase A and Z  and lowercase a to z

Code

package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
rand.Seed(time.Now().Unix())
//Generate a random character between lowercase a to z
randomChar := 'a' + rune(rand.Intn(26))
fmt.Println(string(randomChar))
//Generate a random character between uppercase A and Z
randomChar = 'A' + rune(rand.Intn(26))
fmt.Println(string(randomChar))
//Generate a random character between uppercase A and Z and lowercase a to z
randomInt := rand.Intn(2)
if randomInt == 1 {
randomChar = 'A' + rune(rand.Intn(26))
} else {
randomChar = 'a' + rune(rand.Intn(26))
}
fmt.Println(string(randomChar))
}

Output:

Will be lowercase between a to z
Will be uppercase between A to Z
Will be lowercase between a to z or uppsercase between A to Z
  • character
  • go
  • golang
  • random
  • 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