drsb77336 2015-08-06 06:47
浏览 40

为什么在分配给另一个变量时会擦除字节数组的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{}
}
  • 写回答

2条回答 默认 最新

  • dporb84480 2015-08-06 06:54
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看