Why the extra call to `seed` in this situation?

75 views
Skip to first unread message

Kwaku Biney

unread,
Mar 14, 2023, 6:47:56 PM3/14/23
to golang-nuts
i was digging in the rand package and came across NewSource(seed) in the randpackage which creates a new source in case you don't want the global source set by the package. It returns a Source interface. For some reason, there's a seed method on the Source as well for which Rand implements, where you pass the seed value. But in the NewSource implementation, there's an rng.Seed() which gets called. Is there a reason why these two seed() calls are necessary and if so, anyone know the difference?
https://github.com/golang/go/blob/master/src/math/rand/rand.go (edited) 

Ian Lance Taylor

unread,
Mar 14, 2023, 8:11:11 PM3/14/23
to Kwaku Biney, golang-nuts
On Tue, Mar 14, 2023 at 3:47 PM Kwaku Biney <kwaku...@gmail.com> wrote:
>
> i was digging in the rand package and came across NewSource(seed) in the randpackage which creates a new source in case you don't want the global source set by the package. It returns a Source interface. For some reason, there's a seed method on the Source as well for which Rand implements, where you pass the seed value. But in the NewSource implementation, there's an rng.Seed() which gets called. Is there a reason why these two seed() calls are necessary and if so, anyone know the difference?
> https://github.com/golang/go/blob/master/src/math/rand/rand.go (edited)

A Source requires a seed to do anything at all, so NewSource takes a
seed value. It's possible to change an existing Source to start
producing a new sequence of random numbers starting from a new seed,
so Source has a Seed method. Sure, we could force people to create a
new Source if they want to start a new sequence at a new seed, but
it's easy enough to not require that.

Ian

Kwaku Biney

unread,
Mar 14, 2023, 8:14:36 PM3/14/23
to golang-nuts
Yeah this actually makes sense

```

Reply all
Reply to author
Forward
0 new messages