Golang 创建随机字符串
Golang中的字符串是字符的集合。由于Go中的字符串是不可变的,所以它们在生成后无法被修改。然而,可以通过连接或添加到现有字符串来创建新的字符串。作为Go中的一个内置类型,字符串类型可以像其他任何数据类型一样以多种方式使用。
语法
rand.Seed(value)
Rand.Seed() 函数用于生成随机数。它接受用户输入的参数作为生成随机数的上限。
func Now() Time
Now()函数在时间包中定义。此函数生成当前的本地时间。要使用此函数,我们必须首先在我们的程序中导入时间包。
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 - 创建一个main包,并声明fmt(format包)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包创建随机字符串。输出将是在控制台上生成的随机字符串,并使用Golang的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包来生成随机字符串。这两个程序给出了类似的输出结果。