» Quick Introduction to Go » 2. Intermediate » 2.4 Random

Random

The math/rand package is commonly used for generating pseudorandom numbers. However, it's important to note that the math/rand package is not suitable for cryptographic purposes because it is not secure enough. For cryptographic randomness, you should use the crypto/rand package.

package main

import (
	"fmt"
	"math/rand"
	"time"
)

func main() {
	// Seed the random number generator with the current time
	rand.Seed(time.Now().UnixNano())

	// Generate a random integer between 0 and 100
	randomNumber := rand.Intn(101)
	fmt.Println("Random Number:", randomNumber)
    // => Random Number: 11

	// Generate a random float64 between 0.0 and 1.0
	randomFloat := rand.Float64()
	fmt.Println("Random Float:", randomFloat)
    // => Random Float: 0.21454640863042568
}

Code Challenge

Create a function generateRandomPassword(length int) string that takes the desired length of the password as an argument and returns a randomly generated password.

Loading...
> code result goes here
Prev
Next