Golang : Random Rune generator
Just a quick tutorial on how to generate random runes and add on to previous tutorial on how to generate random string. Useful for generating non-English characters.
Here you go!
package main
import (
"fmt"
"math/rand"
"time"
)
var runes = []rune("一二三四五六七八九十1234567890")
func generateRandomRune(n int) string {
randRune := make([]rune, n)
for i := range randRune {
// without this, the final value will be same all the time.
rand.Seed(time.Now().UnixNano())
randRune[i] = runes[rand.Intn(len(runes))]
}
return string(randRune)
}
func main() {
fmt.Println(generateRandomRune(5))
}
Sample output :
六3十01
p/s : play.golang.org will always show the same random value. You have to test it out on your own machine.
See also : Golang : Count number of runes in string
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+10.1k Golang : Use regular expression to get all upper case or lower case characters example
+6.5k Golang : Map within a map example
+20.7k PHP : Convert(cast) int to double/float
+23.9k Golang : Upload to S3 with official aws-sdk-go package
+30.5k Golang : Remove characters from string example
+8.1k Golang : HttpRouter multiplexer routing example
+10k Golang : Identifying Golang HTTP client request
+6k Javascript : Get operating system and browser information
+5.9k AWS S3 : Prevent Hotlinking policy
+19.8k Golang : Count JSON objects and convert to slice/array
+18k Golang : Convert IPv4 address to decimal number(base 10) or integer
+24.5k Golang : How to print rune, unicode, utf-8 and non-ASCII CJK(Chinese/Japanese/Korean) characters?