企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
### **生成数组** 在线1:<https://play.golang.org/> 在线2:<https://play.studygolang.com/> ```go package main import ( "encoding/json" "fmt" "math/rand" "strings" "time" ) //在线1:https://play.golang.org/ //在线2:https://play.studygolang.com/ func init() { t := time.Now().Add(time.Second * 1).UnixNano() rand.Seed(t) } func main() { ints(10) // 生成整数数组 chars(10) // 生成字符串数组 } func ints(length int) { if length <= 0 { length = 10 } var arr []int for i := 0; i < length; i++ { arr = append(arr, rand.Intn(100)) } s, _ := json.Marshal(arr) nums := strings.Trim(string(s), "[]") fmt.Printf("%s{%s}\n", "var arr = []int", nums) } func chars(length int) { if length <= 0 { length = 10 } var arr []string for i := 0; i < length; i++ { l := 1 t := rand.Intn(6) if t > 0 { l = t } arr = append(arr, monoStr(l)) } for i := 0; i < len(arr); i++ { arr[i] = fmt.Sprintf("\"%s\"", arr[i]) } fmt.Printf("%s{%s}\n", "var chars = []string", strings.Join(arr, ",")) } const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" const ( letterIdxBits = 6 // 6 bits to represent a letter index letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits letterIdxMax = 63 / letterIdxBits // # of letter indices fitting in 63 bits ) var src = rand.NewSource(time.Now().UnixNano()) func monoStr(n int) string { b := make([]byte, n) for i, cache, remain := n-1, src.Int63(), letterIdxMax; i >= 0; { if remain == 0 { cache, remain = src.Int63(), letterIdxMax } if idx := int(cache & letterIdxMask); idx < len(letterBytes) { b[i] = letterBytes[idx] i-- } cache >>= letterIdxBits remain-- } return string(b) } ```