为什么在分配给另一个变量时会擦除字节数组的Golang对象属性

We need to wipe out some variables after use. But it seems really weird when it's assigned with a []byte field in a struct.

Why this assignment of []byte is not a copy but a pointer?

What should I do to keep the value in struct a.bs, but wipe out the b as local variable? http://play.golang.org/p/MT_wAHj2OM

package main

import "fmt"

type so struct {
    bs []byte
}

func zeroes(n int) []byte {
    return make([]byte, n)
}

func wipeBytes(b []byte) {
    copy(b, zeroes(len(b)))
}


func main() {
    a := so{bs: []byte{0x01, 0x02}}
    b := a.bs
    wipeBytes(b)
    fmt.Println(b)    //b == []byte{}
    fmt.Println(a.bs) //a.bs == []byte{}
}

Slices are inherently reference-y things. Assigning one doesn't copy its contents. You can think of a slice value as being a "slice head" structure, which contains a pointer to the slice's underlying array, and the offset and length of the slice within the array. It's this structure that's copied when you copy the slice, not any of the values in the array.

You can do

b := make([]byte, len(a.bs)))
copy(b, a.bs)

to make b a new slice and copy a.bs's contents into it. Then nothing you do to one will have any effect on the other.

When declaring/creating the 'array' ([]byte{0x01, 0x02}), you're not specifying a length ([2]byte{0x01, 0x02}), which means that it's a slice instead of an array. And slices objects internally contains a pointer to it's content.