-
-
Save wuyanxin/54441e530304f008b0c697c230a170f4 to your computer and use it in GitHub Desktop.
使用golang实现一个函数,功能是生成一串6位数的随机数字字符串
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*使用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