Reputation: 377
This code runs and gives a random number from 0 to 999:
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
rand.Seed(time.Now().UnixNano())
fmt.Println(rand.Intn(999))
}
But the following code refuses to run and gives an error
Code:
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
r := rand.Seed(time.Now().UnixNano())
fmt.Println(r.Intn(999))
}
Error message:
rand.Seed(time.Now().UnixNano()) used as value
Note: I'm new to stackOverflow, so if the question isn't according to the rules or standards, please forgive me.
Upvotes: 0
Views: 479
Reputation: 2324
rand.Seed
“sets up” rand.Intn
, if you will. When you call rand.Seed
, it creates a seed that can be used later with rand.Intn
. rand.Intn
returns a value, so
rand.Seed(time.Now().UnixNano())
fmt.Println(rand.Intn(999))
works. But since rand.Seed
does not return a value, calling rand.Intn
on it returns an error.
Upvotes: 0
Reputation: 11
From godoc
Seed uses the provided seed value to initialize the generator to a deterministic state. Seed should not be called concurrently with any other Rand method.
That means, that it set some seed for generating random numbers and don't return anything, but you tried to use it as some value
Upvotes: 1