How to generate a random HEX RGB color code in Go

1 Answer

0 votes
package main

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

func generateRandomHexColor() string {
    const hexChars = "0123456789ABCDEF"
    hex := make([]byte, 6)

    for i := 0; i < 6; i++ {
        index := rand.Intn(16)
        hex[i] = hexChars[index]
    }

    return string(hex)
}

func main() {
    rand.Seed(time.Now().UnixNano()) // Seed the random number generator
    
    hexColor := generateRandomHexColor()
    
    fmt.Printf("Random HEX Color: #%s\n", hexColor)
}



/*
run:

Random HEX Color: #3A05F1

*/

 



answered Oct 10, 2025 by avibootz
...