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
+15.4k Golang : Validate hostname
+17.5k Golang : [json: cannot unmarshal object into Go value of type]
+11.2k Golang : Characters limiter example
+7.6k Golang : Example of how to detect which type of script a word belongs to
+10.9k Golang : Create S3 bucket with official aws-sdk-go package
+17.5k Golang : Defer function inside init()
+5.6k Linux/Unix/PHP : Restart PHP-FPM
+19k Golang : Check if directory exist and create if does not exist
+6.5k Golang : Embedded or data bundling example
+13.4k Golang : Set image canvas or background to transparent
+11.5k Golang : Simple file scaning and remove virus example
+8.6k Golang : Executing and evaluating nested loop in html template