rand.Rand.Seed() vs rand.NewSource()

2,210 views
Skip to first unread message

Liam Breck

unread,
Mar 26, 2019, 2:48:27 PM3/26/19
to golang-nuts
Could anyone clarify the difference between these two?

r := rand.New(rand.NewSource(...))

var r rand.Rand; r.Seed(...)

Ian Lance Taylor

unread,
Mar 26, 2019, 6:25:41 PM3/26/19
to Liam Breck, golang-nuts
Well, it's not a complete program, and maybe I'm missing something,
but it seems to me that the difference is that the first one will give
you a random number generator and the second one will panic at run
time.

Ian

jake...@gmail.com

unread,
Mar 27, 2019, 11:54:38 AM3/27/19
to golang-nuts
Following up on Ian's post. It is generally a good idea to go to the playground and make a minimal working "program" to demonstrate your question before posting. In doing so you would have discovered that the zero value of a rand.Rand can not be used, and will panic.

Also, a tip. You can go to the docs for NewSource at https://golang.org/pkg/math/rand/#NewSource, then click on the "NewSource"  link, and get to the source code at https://golang.org/src/math/rand/rand.go?s=1614:1647#L34, which may be informative.

dja...@gmail.com

unread,
Mar 27, 2019, 12:16:18 PM3/27/19
to golang-nuts
Hi,
I think OP question actually is what is difference  between:
r := rand.New(rand.NewSource(VALUE))

and
r := rand.New(rand.NewSource(ANYTHING))

r
.Seed(VALUE)


Ian Lance Taylor

unread,
Mar 27, 2019, 12:51:55 PM3/27/19
to dja...@gmail.com, golang-nuts
I don't think there is any meaningful difference between those two.

Ian

prrat...@gmail.com

unread,
Feb 10, 2020, 12:09:12 PM2/10/20
to golang-nuts
Seed initialise default resource once for random method and using NewSource create different resources for random method   

anderson...@blacklane.com

unread,
Feb 11, 2020, 4:02:19 AM2/11/20
to golang-nuts
If you use the same seed the source will output the same pseudo-random output. Which is quite useful when you need to be able to replay/predict the random behaviour
Reply all
Reply to author
Forward
0 new messages