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
+27.3k Golang : Decode/unmarshal unknown JSON data type with map[string]interface
+9.1k Golang : Qt Yes No and Quit message box example
+18.1k Golang : Write file with io.WriteString
+29.9k Golang : Generate random string
+15.6k Golang : Get sub string example
+19.4k Golang : How to get time from unix nano example
+6.5k Swift : substringWithRange() function example
+7.4k Golang : Reverse a string with unicode
+9.9k Golang : Convert file unix timestamp to UTC time example
+48k Golang : Upload file from web browser to server
+6.9k Linux : How to fix Brother HL-1110 printing blank page problem
+11.8k Golang : How to check if a string starts or ends with certain characters or words?