首页
/
每日頭條
/
科技
/
golang格式化字符串
golang格式化字符串
更新时间:2025-02-20 12:12:52

随機字符串函數

package main import ( "math/rand" "testing" "time" ) func TestRandomNum(t *testing.T) { n := 10 //指定字符串的長度 //qwertyuio......4567890是需要包含的字符 var letters = []byte("qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM01234567890") //指定長度n,指定類型[]byte result := make([]byte, n) //随機數種子 rand.Seed(time.Now().UnixNano()) //rand.Intn(len(letters)) 返回的是随機的索引值 //letters[rand.Intn(len(letters))] 返回的是根據随機的索引值獲取指定位置的字符 //result[i] : 循環填充result for i := range result { //func Intn(n int) int //Intn以int的形式從默認源返回[0,n]中的一個非負僞随機數。如果n<=0,它将崩潰。 //rand.Seed(86) //fmt.Println(rand.Intn(100)) //fmt.Println(rand.Intn(100)) //fmt.Println(rand.Intn(100)) result[i] = letters[rand.Intn(len(letters))] } // 輸出結果 t.Log(string(result)) }

golang格式化字符串(Golang指定長度的随機字符串)1

源碼截圖

golang格式化字符串(Golang指定長度的随機字符串)2

執行結果

,
Comments
Welcome to tft每日頭條 comments! Please keep conversations courteous and on-topic. To fosterproductive and respectful conversations, you may see comments from our Community Managers.
Sign up to post
Sort by
Show More Comments
Copyright 2023-2025 - www.tftnews.com All Rights Reserved