在Go中,我只想要一个随机字符串(大写或小写),没有数字。最快最简单的方法是什么?


当前回答

简单的解决方案,最少重复的结果:

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

func randomString(length int) string {
    rand.Seed(time.Now().UnixNano())
    b := make([]byte, length+2)
    rand.Read(b)
    return fmt.Sprintf("%x", b)[2 : length+2]
}

在操场上看看

其他回答

package main

import (
    "encoding/base64"
    "fmt"
    "math/rand"
    "time"
)

// customEncodeURL is like `bas64.encodeURL` 
// except its made up entirely of uppercase characters:
const customEncodeURL = "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKL"

// Random generates a random string.
// It is not cryptographically secure.
func Random(n int) string {
    b := make([]byte, n)
    rand.Seed(time.Now().UnixNano())
    _, _ = rand.Read(b) // docs say that it always returns a nil error.

    customEncoding := base64.NewEncoding(customEncodeURL).WithPadding(base64.NoPadding)
    return customEncoding.EncodeToString(b)
}

func main() {
    fmt.Println(Random(16))
}

这里是一个简单而高效的加密安全随机字符串的解决方案。

package main

import (
    "crypto/rand"
    "unsafe"
    "fmt"
)

var alphabet = []byte("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")

func main() {
    fmt.Println(generate(16))
}

func generate(size int) string {
    b := make([]byte, size)
    rand.Read(b)
    for i := 0; i < size; i++ {
        b[i] = alphabet[b[i] % byte(len(alphabet))]
    }
    return *(*string)(unsafe.Pointer(&b))
}

基准

Benchmark  95.2 ns/op      16 B/op      1 allocs/op
/*
    korzhao
*/

package rand

import (
    crand "crypto/rand"
    "math/rand"
    "sync"
    "time"
    "unsafe"
)

// Doesn't share the rand library globally, reducing lock contention
type Rand struct {
    Seed int64
    Pool *sync.Pool
}

var (
    MRand    = NewRand()
    randlist = []byte("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890")
)

// init random number generator
func NewRand() *Rand {
    p := &sync.Pool{New: func() interface{} {
        return rand.New(rand.NewSource(getSeed()))
    },
    }
    mrand := &Rand{
        Pool: p,
    }
    return mrand
}

// get the seed
func getSeed() int64 {
    return time.Now().UnixNano()
}

func (s *Rand) getrand() *rand.Rand {
    return s.Pool.Get().(*rand.Rand)
}
func (s *Rand) putrand(r *rand.Rand) {
    s.Pool.Put(r)
}

// get a random number
func (s *Rand) Intn(n int) int {
    r := s.getrand()
    defer s.putrand(r)

    return r.Intn(n)
}

//  bulk get random numbers
func (s *Rand) Read(p []byte) (int, error) {
    r := s.getrand()
    defer s.putrand(r)

    return r.Read(p)
}

func CreateRandomString(len int) string {
    b := make([]byte, len)
    _, err := MRand.Read(b)
    if err != nil {
        return ""
    }
    for i := 0; i < len; i++ {
        b[i] = randlist[b[i]%(62)]
    }
    return *(*string)(unsafe.Pointer(&b))
}

24.0 ns/op 16 B/op 1 allocs/

使用包uniuri,它生成加密安全的统一(无偏)字符串。

免责声明:我是该软件包的作者

作为icza的出色解决方案的后续,下面我使用rand。读者

func RandStringBytesMaskImprRandReaderUnsafe(length uint) (string, error) {
    const (
        charset     = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
        charIdxBits = 6                  // 6 bits to represent a letter index
        charIdxMask = 1<<charIdxBits - 1 // All 1-bits, as many as charIdxBits
        charIdxMax  = 63 / charIdxBits   // # of letter indices fitting in 63 bits
    )

    buffer := make([]byte, length)
    charsetLength := len(charset)
    max := big.NewInt(int64(1 << uint64(charsetLength)))

    limit, err := rand.Int(rand.Reader, max)
    if err != nil {
        return "", err
    }

    for index, cache, remain := int(length-1), limit.Int64(), charIdxMax; index >= 0; {
        if remain == 0 {
            limit, err = rand.Int(rand.Reader, max)
            if err != nil {
                return "", err
            }

            cache, remain = limit.Int64(), charIdxMax
        }

        if idx := int(cache & charIdxMask); idx < charsetLength {
            buffer[index] = charset[idx]
            index--
        }

        cache >>= charIdxBits
        remain--
    }

    return *(*string)(unsafe.Pointer(&buffer)), nil
}


func BenchmarkBytesMaskImprRandReaderUnsafe(b *testing.B) {
    b.ReportAllocs()
    b.ResetTimer()

    const length = 16

    b.RunParallel(func(pb *testing.PB) {
        for pb.Next() {
            RandStringBytesMaskImprRandReaderUnsafe(length)
        }
    })
}