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
+17.7k Golang : When to use public and private identifier(variable) and how to make the identifier public or private?
+7.5k Golang : Another camera capture GUI application with GTK and OpenCV
+5.1k Golang : Get missing location after unmarshal binary and gob decode time.
+22.1k Golang : minus time with Time.Add() or Time.AddDate() functions to calculate past date
+4k Golang : Print instead of building pyramids
+8k Golang : Serving HTTP and Websocket from different ports in a program example
+15.8k Golang : XML to JSON example
+12.1k Golang : Read from buffered reader until specific number of bytes
+16.1k Golang : Iterate linked list example
+14.9k Golang : Get IP addresses of a domain name
+26.5k Golang : Decode/unmarshal unknown JSON data type with map[string]interface
+29.2k Golang : How to redirect to new page with net/http?