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
+22.8k Golang : Strings to lowercase and uppercase example
+7.3k Golang : Null and nil value
+15.3k Golang : How to add color to string?
+9.9k Golang : Get current, epoch time and display by year, month and day
+10.7k Golang : Create matrix with Gonum Matrix package example
+11.8k Golang : Convert(cast) float to int
+45.2k Golang : Use wildcard patterns with filepath.Glob() example
+5.8k Golang : Struct field tags and what is their purpose?
+24.1k Golang : Fix type interface{} has no field or no methods and type assertions example
+22k Golang : Convert string slice to struct and access with reflect example
+5.9k Golang : Launching your executable inside a console under Linux
+18.4k Golang : Get path name to current directory or folder