LoginSignup
28
25

More than 5 years have passed since last update.

Go言語でランダムな文字列を生成する

Posted at

ランダムな64ビットのintを生成して、基数を36に変更することで、英数混合のランダムな文字列が生成できる。

main.go
package main

import (
    "encoding/binary"
    "crypto/rand"
    "strconv"
)

func main() {
    println(random())
    println(random())
    println(random())
}

func random() string {
    var n uint64
    binary.Read(rand.Reader, binary.LittleEndian, &n)
    return strconv.FormatUint(n, 36)
}

実行結果

g7zxz0xwrlq0
2zy0sbwx1ujlf
2t9t3pqrof5dm

関連

28
25
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
28
25