SoFunction
Updated on 2025-03-05

Implementation method of generating random numbers and random strings in go language

Generate random numbers

The generation of random numbers is a research field in computer science and an art. This is because computers are purely logical machines, so it is very difficult to generate random numbers using computers!

You can use the math/rand package to generate random numbers. Before you start generating random numbers, you need a seed first. The seed is used for initialization of the entire process, which is quite important. Because if you initialize with the same seed every time, you will always get the same sequence of random numbers. This means that everyone can regenerate the same sequence, and this sequence can no longer be considered random!

We will use the program to generate random numbers as the name of , which is divided into four parts to introduce below. This program requires several parameters, namely, the lower limit of generating a random number, the upper limit of generating a random number, and the number of generating a random number. If you also use the fourth command parameter, the program will seed the random number generator. During testing, you can use this parameter again to generate the same sequence.

The first part of the program is as follows:

package main

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

func random(min, max int) int {
    return (max-min) + min
}

The random() function does all the work, and it generates random numbers by calling () based on the specified range.

The second part of this command line program is as follows:

func main() {
    MIN := 0
    MAX := 100
    TOTAL := 100
    SEED := ().Unix()

    arguments := 

This section initializes the variables that will be used in the program.

The third part of the Go code is as follows:

    switch len(arguments) {
    case 2:
        ("Usage: ./randomNumbers MIN MAX TOTAL SEED")
        MIN, _ = (arguments[1])
        MAX = MIN + 100
    case 3:
        ("Usage: ./randomNumbers MIN MAX TOTAL SEED")
        MIN, _ = (arguments[1])
        MAX, _ = (arguments[2])
    case 4:
        ("Usage: ./randomNumbers MIN MAX TOTAL SEED")
        MIN, _ = (arguments[1])
        MAX, _ = (arguments[2])
        TOTAL, _ = (arguments[3])
    case 5:
        MIN, _ = (arguments[1])
        MAX, _ = (arguments[2])
        TOTAL, _ = (arguments[3])
        SEED, _ = (arguments[4], 10, 64)
    default:
        ("Using default values!")
    }

The logic behind the switch code block is relatively simple: Determine whether the parameters in the program use the default default value or the user-provided value based on the number of command line parameters. To simplify the program, the error parameters returned by the () and () functions are received using an underscore character and are then ignored. If it is a commercial program, you must not ignore the error parameters returned by the () and () functions!

Finally, using () to assign a new value to the SEED variable is because the parameter type required by the () function is int64. The first parameter of () is the string to be parsed, the second parameter is the cardinality of the output number, and the third parameter is the number of bits of the output number. Since we want to generate a 64-bit decimal integer, use 10 as the cardinality and 64 as the digits. Note that if you want to parse unsigned integers, you should use the () function instead.

The last part is the following Go code:

    (SEED)
    for i := 0; i < TOTAL; i++ {
        myrand := random(MIN, MAX)
        (myrand)
        (" ")
    }
    ()
}

In addition to using Unix timestamps as seeds of random number generators, you can also use the /dev/random system device. You can learn about /dev/random in Chapter 8 “Go Unix System Programming”.

Execute will generate the following output:

$ go run 
75 69 15 75 62 67 64 8 73 1 83 92 7 34 8 70 22 58 38 8 54 91 65 1 50 76 5 82 61 90 10 38 40 63 6 28 51 54 49 27 52 92 76 35 44 9 66 76 90 10 29 22 20 83 33 92 80 50 62 26 19 45 56 75 40 30 97 23 87 10 43 11 42 65 80 82 25 53 27 51 99 88 53 36 37 73 52 61 4 81 71 57 30 72 51 55 62 63 79
$ go run  1 3 2
Usage: ./randomNumbers MIN MAX TOTAL SEED
1 1 
$ go run  1 3 2
Usage: ./randomNumbers MIN MAX TOTAL SEED
2 2
$ go run  1 5 10 10
3 1 4 4 1 1 4 4 4 3
$ go run  1 5 10 10
3 1 4 4 1 1 4 4 4 3

If you are really interested in random number generation, you should first read the second volume of The Art of Computer Programming (Addison-Wesley Professional, 2011) written by Donald.

If you need to use Go to generate safer random numbers, you can use the crypto/rand package. This package implements a pseudo-random number generator that satisfies cryptographic security. You can/pkg/crypto/rand/The documentation page learns more about the crypto/rand package.

Generate random strings

Once you know how a computer presents a single character, it's not difficult to transition from a random number to a random string. This section will introduce how to use the code in the previous section to generate hard-to-guess passwords. The Go program used to complete this task is called , which will be introduced in four parts below. This program only requires one command line parameter, which is the length of the password you need to generate.

The first part contains the following Go code:

package main

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

func random(min, max int) int {
    return (max-min) + min
}

The second code segment is as follows:

func main() {
    MIN := 0
    MAX := 94
    SEED := ().Unix()
    var LENGTH int64 = 8

    arguments := 

We only want to get printable ASCII characters, so we limit the range of random numbers to generate. There are 94 characters that can be printed in the ASCII character table. This means that the range of random numbers generated by the program should be from 0 to 94 and exclude 94.

The third code segment is as follows:

    switch len(arguments) {
    case 2:
        LENGTH, _ = ([1], 10, 64)
    default:
        ("Using default values!")
    }

       (SEED)

The last part is as follows:

    startChar := "!"
    var i int64 = 1
    for {
        myRand := random(MIN, MAX)
        newChar := string(startChar[0] + byte(myRand))
        (newChar)
        if i == LENGTH {
            break
        }
        i++
    }
    ()
}

The startChar parameter saves the first ASCII character that this program can generate, that is, the exclamation point with a decimal ASCII value of 33. It is known that the random number generated by this program is less than 94, and the maximum generated ASCII value can be calculated as 93 + 33, equal to 126, that is, the ASCII value of ~. The following output is an ASCII character table containing decimal values:

The decimal set:

  0 nul    1 soh    2 stx    3 etx    4 eot    5 enq    6 ack    7 bel
  8 bs     9 ht    10 nl    11 vt    12 np    13 cr    14 so    15 si
 16 dle   17 dc1   18 dc2   19 dc3   20 dc4   21 nak   22 syn   23 etb
 24 can   25 em    26 sub   27 esc   28 fs    29 gs    30 rs    31 us
 32 sp    33  !    34  "    35  #    36  $    37  %    38  &    39  '
 40  (    41  )    42  *    43  +    44  ,    45  -    46  .    47  /
 48  0    49  1    50  2    51  3    52  4    53  5    54  6    55  7
 56  8    57  9    58  :    59  ;    60  <    61  =    62  >    63  ?
 64  @    65  A    66  B    67  C    68  D    69  E    70  F    71  G
 72  H    73  I    74  J    75  K    76  L    77  M    78  N    79  O
 80  P    81  Q    82  R    83  S    84  T    85  U    86  V    87  W
 88  X    89  Y    90  Z    91  [    92  \    93  ]    94  ^    95  _
 96  `    97  a    98  b    99  c   100  d   101  e   102  f   103  g
104  h   105  i   106  j   107  k   108  l   109  m   110  n   111  o
112  p   113  q   114  r   115  s   116  t   117  u   118  v   119  w
120  x   121  y   122  z   123  {   124  |   125  }   126  ~   127 del

Enter man ascii into your favorite Unix shell to generate an easy-to-read ASCII character table.

Execute and pass in the appropriate command line parameters will generate the following output:

$ go run 
Using default values!
ugs$5mv1
$ go run 
Using default values!
PA/8hA@?
$ go run  20
HBR+=3\UA'B@ExT4QG|o
$ go run  20
XLcr|R{*pX/::'t2u^T'

This is the article about the implementation method of generating random numbers and random strings in Go language. For more related contents of generating random numbers and random strings in Go language, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!