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.9k Golang : Google Drive API upload and rename example
+19.2k Golang : Delete item from slice based on index/key position
+9.4k Golang : Extract or copy items from map based on value
+22.4k Golang : How to read JPG(JPEG), GIF and PNG files ?
+10k Golang : Test a slice of integers for odd and even numbers
+9.6k Golang : Quadratic example
+5.1k Golang : Print instead of building pyramids
+5.1k Python : Create Whois client or function example
+9.5k Golang : How to extract video or image files from html source code
+7.5k SSL : How to check if current certificate is sha1 or sha2 from command line
+4.9k Golang : Calculate a pip value and distance to target profit example
+8.8k Yum Error: no such table: packages