Golang 指定长度随机数
//指定位数随机数
//使用包 crypto/rand func CreateRandomNumber(len int) string{ var numbers = []byte{1,2,3,4,5,7,8,9} var container string length := bytes.NewReader(numbers).Len() for i:=1;i<=len;i++{ random,err := rand.Int(rand.Reader,big.NewInt(int64(length))) if err != nil { } container += fmt.Sprintf("%d",numbers[random.Int64()]) } return container }
随机字符串
import ( "math/big" "bytes" "crypto/rand" "github.com/go-ffmt/ffmt" ) func main() { randomStr := CreateRandomString(15) ffmt.P(randomStr) //string("mCvYEd8MH8xnBRn") } func CreateRandomString(len int) string { var container string var str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890" b := bytes.NewBufferString(str) length := b.Len() bigInt := big.NewInt(int64(length)) for i := 0;i < len ;i++ { randomInt,_ := rand.Int(rand.Reader,bigInt) container += string(str[randomInt.Int64()]) } return container }