go - How to extract character from array in golang? -


need extract random characters string

here got:

const letterbytes = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"   b := make([]byte, 1) := range b {     b[i] = letterbytes[rand.intn(len(letterbytes))] } fmt.println(string(b)) 

but returns "x" but, need return every time new character using rand function. appreciated. thanks.

start seeding pseudorandom number generator. example,

package main  import (     "fmt"     "math/rand"     "time" )  func main() {     rand.seed(time.now().unixnano())     const letterbytes = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"     b := make([]byte, 7)     := range b {         b[i] = letterbytes[rand.intn(len(letterbytes))]     }     fmt.println(string(b)) } 

output:

jfxtysc 

the go playground

about playground

in playground time begins @ 2009-11-10 23:00:00 utc (determining significance of date exercise reader). makes easier cache programs giving them deterministic output.

therefore, in go playground, time.now().unixnano() returns same value. random seed value, run code on computer.


for unicode code point (go rune),

package main  import (     "fmt"     "math/rand"     "time" )  package main  import (     "fmt"     "math/rand"     "time" )  func main() {     rand.seed(time.now().unixnano())     chars := []rune("abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz世界!@=")     r := make([]rune, 50)     := range r {         r[i] = chars[rand.intn(len(chars))]     }     fmt.println(string(r)) } 

output:

世qrysp=@gijmikly=txrefjtvkee!yhhtsqhvlyuydrnibbilw 

Comments

Popular posts from this blog

python - Operations inside variables -

Generic Map Parameter java -

arrays - What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it? -