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
+4.3k Golang : Missing Subversion command
+27k error: trying to remove "yum", which is protected
+2k Java : Get FX sentiment from website example
+14.1k Golang : Get download file size
+7.8k Golang : Underscore string example
+17.1k Golang : Generate MD5 checksum of a file
+4.9k Golang : Totalize or add-up an array or slice example
+16.4k Golang : Check if directory exist and create if does not exist
+9.2k Golang : Simple client-server HMAC authentication without SSL example
+3.5k Responsive Google Adsense
+5.8k Golang : Get final or effective URL with Request.URL example
+8.5k Golang : How to flush a channel before the end of program?