package main import ( "fmt" "math/rand" "strings" ) const ( // As we only want to get printable ASCII characters, we limit the range of pseudo-random numbers // that can be generated. The total number of printable characters in the ASCII table is 94. This means // that the range of the pseudo-random numbers that the program can generate should be from 0 // to 94, without including 94. Therefore, the values of the MIN and MAX global variables, // are 0 and 94, respectively. MIN = 0 MAX = 94 ) func main() { fmt.Println(randString(20)) } func randInt(min, max int) int { // Intn returns, as an int, a non-negative pseudo-random number in the half-open interval [0,n) from the default [Source]. It panics if n <= 0. return rand.Intn(max - min) + min } func randString(len int64) string { // The startChar variable holds the first ASCII character that can be generated by the utility, which, // in this case, is the exclamation mark, which has a decimal ASCII value of 33. startChar := "!" sb := strings.Builder{} var i int64 = 1 for { myRand := randInt(MIN, MAX) newChar := string(startChar[0] + byte(myRand)) sb.WriteString(newChar) if i == len { break } i++ } return sb.String() }
标签:randInt,int,randString,func,Zgo,ASCII,94 From: https://www.cnblogs.com/zhangzhihui/p/18240849