2 回答

TA貢獻2003條經驗 獲得超2個贊
正如已經建議的那樣,您真的應該考慮使用encoding/csv
.
也就是說,您的問題的原因在函數上方的 godocBytes()
中進行了解釋:
// Bytes returns the most recent token generated by a call to Scan.
// The underlying array may point to data that will be overwritten
// by a subsequent call to Scan. It does no allocation.
func (s *Scanner) Bytes() []byte {
return s.token
}
因此,返回的字節切片可能會被后續調用修改Scan()。為避免這種情況,您需要復制字節切片,例如
for scanner.Scan() {
row := scanner.Bytes()
bs := make([]byte, len(row))
copy(bs, row)
b.Append(bs)
}

TA貢獻1854條經驗 獲得超8個贊
您需要創建 返回的數據的副本Bytes。
https://pkg.go.dev/[email protected]#Scanner.Bytes
Bytes 返回調用 Scan 生成的最新標記。底層數組可能指向將被后續調用 Scan 覆蓋的數據。它沒有分配。
for scanner.Scan() {
row := make([]byte, len(scanner.Bytes()))
copy(row, scanner.Bytes())
b.Append(row)
}
https://go.dev/play/p/Lqot-wOXiwh
- 2 回答
- 0 關注
- 152 瀏覽
添加回答
舉報