Skip to content

Instantly share code, notes, and snippets.

@wuyanxin
Forked from axiaoxin/generateRandomDigits.go
Last active January 24, 2025 07:24
Show Gist options
  • Save wuyanxin/54441e530304f008b0c697c230a170f4 to your computer and use it in GitHub Desktop.
Save wuyanxin/54441e530304f008b0c697c230a170f4 to your computer and use it in GitHub Desktop.
使用golang实现一个函数,功能是生成一串6位数的随机数字字符串
/*使用golang实现一个函数,功能是生成一串6位数的随机数字字符串*/
package main
import (
"fmt"
"math/rand"
"time"
)
var digits = []rune("0123456789")
var seed = rand.NewSource(time.Now().UnixNano()) // create a random number generator with the seed
var rng = rand.New(seed)
func GenPinCode(keyLen int) string {
if keyLen < 1 {
keyLen = 6
}
result := make([]rune, keyLen)
// loop n times and append a random digit to the result
for i := range result {
result[i] = digits[rng.Intn(len(digits))]
}
return string(result)
}
func main() {
fmt.Println(GenPinCode(6))
fmt.Println(GenPinCode(6))
fmt.Println(GenPinCode(6))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment