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
+5.8k nginx : force all pages to be SSL
+35.5k Golang : Get file last modified date and time
+12k Golang : 2 dimensional array example
+8.2k Golang : How to check variable or object type during runtime?
+4.5k Unix/Linux : How to pipe/save output of a command to file?
+9.9k Golang : Compare files modify date example
+10.3k Golang : Resolve domain name to IP4 and IP6 addresses.
+11.5k Golang : GTK Input dialog box examples
+10.3k Golang : Get local time and equivalent time in different time zone
+9.4k Golang : Find correlation coefficient example
+25.9k Golang : Get executable name behind process ID example
+5.3k Golang : Detect words using using consecutive letters in a given string