Generate random hex string in Go

In Ruby you can call a simple and convenient function SecureRandom.hex to make a string of preferred size filled with hexadecimals.


require "secureranom"
# => bfa620013597e9c30c179037ad74527a4956a561

Here's a quick snippet of how to make its alternative in Go:

package main

import (

func randomHex(n int) (string, error) {
  bytes := make([]byte, n)
  if _, err := rand.Read(bytes); err != nil {
    return "", err
  return hex.EncodeToString(bytes), nil

func main() {
  val, _ := randomHex(20)

Run example