Go 函数改变字节片参数

Go 函数改变字节片参数,go,bytearray,Go,Bytearray,我有下面的代码,其中我有一个字母表的字节片,我将这个字母表数组复制到一个新变量(cryptkey)中,并使用一个函数将其洗牌。结果是字母表和密钥字节片被洗牌。我怎样才能防止这种情况发生 package main import ( "fmt" "math/rand" ) func main() { alphabet := []byte("ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz.") cryptk

我有下面的代码,其中我有一个字母表的字节片,我将这个字母表数组复制到一个新变量(cryptkey)中,并使用一个函数将其洗牌。结果是字母表和密钥字节片被洗牌。我怎样才能防止这种情况发生

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
}
结果:

ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvxyz。 miclOfEInzJNvZe.YuVMCdTbXyqtaLwHGjUrABhog xQPWSpKRkDsF


!

复制一份。比如说,

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
}
输出:

ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz.
ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz.

要实现的关键是,[]字节是字节片,而不是字节数组。这意味着可以将其视为指向底层数组的指针。