Go語言生成隨機字串的程式


Go 語言中的字串是字元的集合。由於 Go 語言中的字串是不可變的,因此在生成後無法修改它們。但是,連線或新增到現有字串可以建立新的字串。字串型別是 Go 語言中的內建型別,可以像其他任何資料型別一樣以多種方式使用。

語法

rand.Seed(value)

Rand.Seed() 函式用於生成隨機數。它接受使用者輸入作為引數,該引數是生成隨機數的上限。

func Now() Time

Now() 函式定義在 time 包中。此函式生成當前本地時間。要使用此函式,我們必須首先在程式中匯入 time 包。

func (t Time) UnixNano() int64

UnixNano() 函式定義在 time 包中。此函式用於獲取自 1970 年 1 月 1 日 UTC 時間以來經過的秒數。它返回的最終結果是 64 位整數型別。

rand.Intn(n)

Intn() 函式定義在 math/rand 包中。它用於在 [0, n] 區間內生成隨機數,其中 n 是使用者提供的數字。如果提供的數字小於 0,則該函式會丟擲錯誤。

func make ([] type, size, capacity)

Go 語言中的 make 函式用於建立陣列/對映,它接受要建立的變數的型別、大小和容量作為引數。

rand.Read(output)

read 函式用於生成密碼學安全的隨機位元組流。生成的隨機位元組被放置到 []byte 切片中,這是它接受的唯一引數。如果該函式返回錯誤,則不應使用它。

演算法

  • 步驟 1 − 建立一個 package main 並宣告 fmt(格式包)、math/rand 和 time 包

  • 步驟 2 − 建立一個常量集

  • 步驟 3 − 開始 main 函式()

  • 步驟 4 − 使用內部函式建立隨機字串

  • 步驟 5 − 使用 string() 方法將位元組段轉換為字串

  • 步驟 6 − 使用 fmt.Println() 函式(其中 ln 表示換行)在控制檯上列印獲得的隨機字串。

示例 1

在這個例子中,我們將學習如何使用 math/rand 包建立隨機字串,這裡將構造一個字元集,從中將使用 rand/math 包在控制檯上列印隨機字串。

package main
import (
	"fmt"
	"math/rand"
	"time"
)

//create character set
const set = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"

func main() {
	rand.Seed(time.Now().UnixNano())
	fmt.Println("The character set given here is:", set)
	length := 20
	output := make([]byte, length)
	for i := range output {
		output[i] = set[rand.Intn(len(set))] //random characters generated from the above set
	}
	fmt.Println("The set of random characters is:")
	fmt.Println(string(output))  //print the output after converting it to string
}

輸出

The character set given here is: abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
The set of random characters is:
nV6EakoP6yBy8qtCwuvC

示例 2

在這個例子中,我們將看到如何使用 crypto/rand 包建立隨機字串。輸出將是在控制檯上生成的隨機字串,並使用 Go 語言中的 print 語句列印。

package main
import (
	"crypto/rand"
	"fmt"
)

func main() {
	length := 10
	output := make([]byte, length)  //create output slice of bytes
	_, err := rand.Read(output) //function reads the error
	if err != nil {
		fmt.Println(err)  //print the error 
		return
	}
   fmt.Println("The set of random characters is:")
	fmt.Println(string(output)) //print random characters
}

輸出

The set of random characters is:
6

結論

我們使用兩個例子執行了生成隨機字串的程式。在第一個例子中,我們使用 math/rand 包和一個字元集,在第二個例子中,我們使用 crypto/rand 包生成隨機字串。這兩個程式都給出了類似的輸出。

更新於:2023年7月19日

瀏覽量:119

開啟你的 職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.