函数改变字节切片参数



我有以下代码,其中我有一段带有字母表的字节,我将这个字母数组复制到一个新变量(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 abcdefghijklmnopqrstuvwxyz. 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.

最新更新