我正在嘗試重新實現(xiàn)它幾年前在 Go中用C 完成的程序該程序應(yīng)該讀取一個類似于“記錄”的結(jié)構(gòu)化二進制文件并對記錄做一些事情(對記錄本身所做的事情與此無關(guān))問題)這樣的數(shù)據(jù)文件由許多記錄組成,其中每條記錄具有以下定義:REC_LEN U2 // length of record after headerREC_TYPE U1 //a typeREC_SUB U1 //a subtypeREC_LEN x U1 //"payload" 我現(xiàn)在的問題是如何在 Go 的結(jié)構(gòu)中指定可變長度字節(jié) []?我的計劃是使用 binary.Read 來讀取記錄這是我迄今為止在 Go 中嘗試過的:type Record struct { rec_len uint16 rec_type uint8 rec_sub uint8 data [rec_len]byte}不幸的是,我似乎無法在同一結(jié)構(gòu)中引用結(jié)構(gòu)的字段,因為出現(xiàn)以下錯誤:xxxx.go:15: undefined: rec_lenxxxx.go:15: invalid array bound rec_len我很感激任何給我指明正確方向的想法
1 回答

守著星空守著你
TA貢獻1799條經(jīng)驗 獲得超8個贊
您可以按如下方式讀取記錄:
var rec Record
// Slurp up the fixed sized header.
var buf [4]byte
_, err := io.ReadFull(r, buf[:])
if err != nil {
// handle error
}
rec.rec_len = binary.BigEndian.Uint16(buf[0:2])
rec.rec_type = buf[2]
rec.rec_sub = buf[3]
// Create the variable part and read it.
rec.data = make([]byte, rec.rec_len)
_, err = io.ReadFull(r, rec.data)
if err != nil {
// handle error
}
- 1 回答
- 0 關(guān)注
- 340 瀏覽
添加回答
舉報
0/150
提交
取消