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
+8.3k Golang : Variadic function arguments sanity check example
+9.2k Golang : Inject/embed Javascript before sending out to browser example
+18.5k Golang : Put UTF8 text on OpenCV video capture image frame
+18.6k Golang : Write file with io.WriteString
+22.9k Golang : Set and Get HTTP request headers example
+18.3k Golang : Check if a directory exist or not
+7.1k Android Studio : Hello World example
+5.6k Golang : Display advertisement images or strings on random order
+6.5k PHP : How to handle URI or URL with non-ASCII characters such as Chinese/Japanese/Korean(CJK) ?
+5.8k Golang : Error handling methods
+6.6k Golang : Break string into a slice of characters example
+8.4k Golang : Metaprogramming example of wrapping a function