go slice踩到的坑

最近用go,发现go slice 处理的时候,如果输入的长度满足要求则不会重新分配空间,长度不够的话重新分配空间

测试代码:

func PackDataCRC32(plainData []byte) []byte {

    ieee := crc32.NewIEEE()

    ieee.Write(plainData)

    s := ieee.Sum32()

    b := make([]byte, 4)

    binary.BigEndian.PutUint32(b, s)

 

    return append(plainData, b...)

}

func  main {

    testBytes := make([]byte, 10)

    testBytes2 := make([]byte, 20)

    fmt.Printf("Before:testBytes2 %p val is %v \r\n", testBytes2, testBytes2)

    fmt.Printf("Before:testBytes %p val is %v \r\n", testBytes, testBytes)

    PackDataCRC32(testBytes)

    fmt.Printf("After: testBytes %p val is %v \r\n", testBytes, testBytes)

 

    testBytes3 := testBytes2[:10]

    fmt.Printf("Before:testBytes3 %p val is %v \r\n", testBytes3, testBytes3)

    fmt.Printf("Before:testBytes2 %p val is %v \r\n", testBytes2, testBytes2)

    PackDataCRC32(testBytes3, secretKey)

    fmt.Printf("After: testBytes3 %p val is %v \r\n", testBytes3, testBytes3)

    fmt.Printf("After: testBytes2 %p val is %v \r\n", testBytes2, testBytes2)

}

输出:

Before:testBytes2 0xc42001a4c0 val is [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
Before:testBytes  0xc420018690 val is [0 0 0 0 0 0 0 0 0 0]
plainText 0xc420018690 , plainTextWithCrc 0xc42001a4e0
After: testBytes  0xc420018690 val is [0 0 0 0 0 0 0 0 0 0]
Before:testBytes3 0xc42001a4c0 val is [0 0 0 0 0 0 0 0 0 0]
Before:testBytes2 0xc42001a4c0 val is [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
plainText 0xc42001a4c0 , plainTextWithCrc 0xc42001a4c0
After: testBytes3 0xc42001a4c0 val is [0 0 0 0 0 0 0 0 0 0]
After: testBytes2 0xc42001a4c0 val is [0 0 0 0 0 0 0 0 0 0 227 138 104 118 0 0 0 0 0 0]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值