Give seed value to the Seed func in math/rand package. Otherwise the same
string is returned on every time.
Accoding to the comment from @dchapes, the pseudorandom number generator
should not be re-seeded on each use, nor re-seed the global PRNG in a
package. @shurcooL shows how to properly seed the PRNG:
If you're using global rand.Rand, don't re-seed it. But if you want to
set your own seed, create your own local instance of rand.Rand.
varr*rand.Rand// Rand for this package.funcinit(){r=rand.New(rand.NewSource(time.Now().UnixNano()))}funcRandomString(strlenint)string{// use existing r, no need to re-seed itr.Intn(len(chars))}
(Note that time package in Go Playground always returns the same value no
matter what current time is, so the generated string will always be the same on
Go Playground)
packagemylibimport("math/rand""time")varr*rand.Rand// Rand for this package.funcinit(){r=rand.New(rand.NewSource(time.Now().UnixNano()))}funcRandomString(strlenint)string{constchars="abcdefghijklmnopqrstuvwxyz0123456789"result:=make([]byte,strlen)fori:=rangeresult{result[i]=chars[r.Intn(len(chars))]}returnstring(result)}
packagemylibimport("math/rand""time")varr*rand.Rand// Rand for this package.funcinit(){r=rand.New(rand.NewSource(time.Now().UnixNano()))}funcRandomString2(strlenint)string{constchars="abcdefghijklmnopqrstuvwxyz0123456789"result:=""fori:=0;i<strlen;i++{index:=r.Intn(len(chars))result+=chars[index:index+1]}returnresult}