A problem background
In recent projects, random numbers are used to deal with random problems. During the testing process, the project suddenly reported an error: invalid argument to intn; the prompt is as follows:
The second reason for the problem
The random function I use here is the golang built-in package rand
, the method used is rand.Intn
, the input parameter of this method is a non-negative number; then the return value is The random number between [0,n)
; when I use it here, I do not judge the input parameter n
, in some cases, the input parameter n
will become 0, which is why the above error is reported: invalid argument to intn
In fact, this error is a prompt in the source code implementation of the random function; when the incoming parameter is less than or equal to 0, this prompt will be thrown; the example demo is as follows:
package main import ( "fmt" "math/rand"