函数改变字节切片参数

时间:2014-12-13 15:32:16

标签: go bytearray

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

Playground

1 个答案:

答案 0 :(得分:3)

制作副本。例如,

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.