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
+13.1k Facebook PHP getUser() returns 0
+21.8k Golang : Securing password with salt
+9.9k Golang : Detect number of faces or vehicles in a photo
+9.8k Golang : Read file and convert content to string
+14.9k Golang : Get HTTP protocol version example
+7.9k Golang : How To Use Panic and Recover
+9.3k Golang : Read file with ioutil
+5.3k PHP : Fix Call to undefined function curl_init() error
+10.5k Golang : Command line file upload program to server example
+51.9k Golang : How to get struct field and value by name
+17.2k Golang : Clone with pointer and modify value