rand.Intn always returns "1"

Just a quick question: Why my function always returns “1”?

fmt.Println(rand.Intn(10))

I read that If you use go playground, you may encounter such problems - but It appears as well while using my PC console. Hilfe :slight_smile:

1 Like

Ich werde dir helfen! :smile:

Are you using math/rand or crypto/rand? The former will always generate the same sequence of pseudorandom numbers unless you seed its Source. From the documentation:

Random numbers are generated by a Source. Top-level functions, such as Float64 and Int, use a default shared Source that produces a deterministic sequence of values each time a program is run. Use the Seed function to initialize the default Source if different behavior is required for each run.

I’m using math/rand. I tried crypto/rand, but It won’t recognise “rand.Intn” now :laughing: there is probably a different function for crypto/rand, right? “Crypto/intn(10)” won’t work as well :sweat_smile:

What are you doing with the randomly generated numbers? Do they need to be cryptographically secure, or are pseudorandom numbers sufficient? If math/rand.Intn is good enough for you, and you just want the numbers to be less predictable, I would recommend:

  • Create a new math/rand.Source with math/rand.NewSource.

    One way you could get a pseudorandom seed to pass into rand.NewSource is by using the current time (call time.Now and then call the UnixNano method on it to get a somewhat random int64 value).

  • Pass that seed into math/rand.New to create a new random number generator (call it, for example, myRand).

  • Instead of calling math/rand.Intn, now you can use your separate myRand generator and call Intn on that.

Pseudorandom number is sufficient, just need to check If the other part of my code works. I’m a total newbie and I didn’t fully understand the steps you decribed ( :rofl: ). I mean, I get the idea of the “source” or “seed” that is required for generating pseudorandom numbers, and why current date would be a good starting point. I tried this:

rand.Seed(time.Now())
fmt.Println(rand.Intn(10))

but I got this:

cannot use time.Now() (value of type time.Time) as type int64 in argument to rand.Seed

As I understand correctly, I need to convert the date to a number to fix the issue.
Or read again your reply and try to figure it out :slight_smile:

Call time.Now().UnixNano() to get an int64

1 Like

rand.Seed(time.Now().UnixNano())
fmt.Println(rand.Intn(10))

Now it works, thanks a lot!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.