dreamy6301 2014-12-13 07:32
浏览 49
已采纳

函数更改字节片参数

I have the following code where I have a slice of bytes with the alphabet, I copy this alphabet array in a new variable (cryptkey) and I use a function to shuffle it. The result is that the alphabet and the cryptkey byte slice get shuffled. How can I prevent this from happening?

package main

import (
    "fmt"
    "math/rand"
)

func main() {
    alphabet := []byte("ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz.")
    cryptkey := alphabet
    fmt.Println(string(alphabet))
    cryptkey = shuffle(cryptkey)
    fmt.Println(string(alphabet))
}

func shuffle(b []byte) []byte {
    l := len(b)
    out := b
    for key := range out {
        dest := rand.Intn(l)
        out[key], out[dest] = out[dest], out[key]
    }
    return out
}

Result :

ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz. miclOfEInzJNvZe.YuVMCdTbXyqtaLwHGjUrABhog xQPWSpKRkDsF

Playground!

展开全部

  • 写回答

1条回答 默认 最新

  • douci6541 2014-12-13 07:39
    关注

    Make a copy. For example,

    package main
    
    import (
        "fmt"
        "math/rand"
    )
    
    func main() {
        alphabet := []byte("ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz.")
        cryptkey := alphabet
        fmt.Println(string(alphabet))
        cryptkey = shuffle(cryptkey)
        fmt.Println(string(alphabet))
    }
    
    func shuffle(b []byte) []byte {
        l := len(b)
        out := append([]byte(nil), b...)
        for key := range out {
            dest := rand.Intn(l)
            out[key], out[dest] = out[dest], out[key]
        }
        return out
    }
    

    Output:

    ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz.
    ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz.
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?