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
+12.3k Golang : Set image canvas or background to transparent
+4.3k Golang : The Tao of importing package
+14.7k Golang : Generate universally unique identifier(UUID) example
+4.7k Swift : Get substring with rangeOfString() function example
+16.1k Golang : How to make a file read only and set it to writable again?
+11.6k Golang : Convert int(year) to time.Time type
+9.1k Golang : Read file and convert content to string
+11k Android Studio : Highlight ImageButton when pressed on example
+14.1k Golang : How to login and logout with JWT example
+4.8k Unix/Linux : Get reboot history or check when was the last reboot date
+6.2k Golang : Check if one string(rune) is permutation of another string(rune)
+9k Golang : Print how to use flag for your application example