英文:
Function mutates byte slice argument
问题
我有以下代码,其中我有一个字节切片包含字母表,我将这个字母表复制到一个新变量(cryptkey)中,并使用一个函数对其进行洗牌。结果是字母表和cryptkey字节切片被洗牌了。我该如何防止这种情况发生?
package main
import (
"fmt"
"math/rand"
)
func main() {
alphabet := []byte("ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz.")
cryptkey := make([]byte, len(alphabet))
copy(cryptkey, alphabet)
fmt.Println(string(alphabet))
cryptkey = shuffle(cryptkey)
fmt.Println(string(alphabet))
}
func shuffle(b []byte) []byte {
l := len(b)
out := make([]byte, l)
copy(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
英文:
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
答案1
得分: 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.
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论