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]

猜你喜欢

转载自blog.csdn.net/bebest2010/article/details/82721727