ds34222222 2014-01-07 19:05
浏览 105
已采纳

Golang:如何从缓冲区读取内容时跳过结构字段?

http://play.golang.org/p/RQXB-hCq_M

type Header struct {
    ByteField1 uint32    // 4 bytes
    ByteField2 [32]uint8 // 32 bytes
    ByteField3 [32]uint8 // 32 bytes
    SkipField1 []SomethingElse
}

func main() {
    var header Header
    headerBytes := make([]byte, 68)  // 4 + 32 + 32 == 68
    headerBuf := bytes.NewBuffer(headerBytes)
    err := binary.Read(headerBuf, binary.LittleEndian, &header)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(header)
}

I don't want to read from the buffer into the header struct in chunks. I want to read into the bytefield in one step but skip non byte fields. If you run the program in the given link (http://play.golang.org/p/RQXB-hCq_M) you will find that binary.Read to throw an error: binary.Read: invalid type []main.SomethingElse

Is there a way that I can skip this field?

Update: Based on dommage's answer, I decided to embed the fields inside the struct instead like this http://play.golang.org/p/i0xfmnPx4A

  • 写回答

1条回答 默认 最新

  • dongsaolian8786 2014-01-07 19:45
    关注

    You can cause a field to be skipped by prefixing it's name with _ (underscore).

    But: binary.Read() requires all fields to have a known size. If SkipField1 is of variable or unknown length then you have to leave it out of your struct.

    You could then use io.Reader.Read() to manually skip over the skip field portion of your input and then call binary.Read() again.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启