常规错误处理

    1. var p Point
    2. if err := binary.Read(r, binary.BigEndian, &p.Longitude); err != nil {
    3. return nil, err
    4. }
    5. if err := binary.Read(r, binary.BigEndian, &p.Latitude); err != nil {
    6. return nil, err
    7. }
    8. if err := binary.Read(r, binary.BigEndian, &p.Distance); err != nil {
    9. return nil, err
    10. }
    11. if err := binary.Read(r, binary.BigEndian, &p.ElevationGain); err != nil {
    12. return nil, err
    13. }
    14. if err := binary.Read(r, binary.BigEndian, &p.ElevationLoss); err != nil {
    15. return nil, err
    16. }

    参考bufio.Scanner()的错误处理

    1. scanner := bufio.NewScanner(input)
    2. for scanner.Scan() {
    3. token := scanner.Text()
    4. // process token
    5. }
    6. if err := scanner.Err(); err != nil {
    7. // process the error
    8. }

    优化

    1. type Reader struct {
    2. r io.Reader
    3. err error
    4. }
    5. func (r *Reader) read(data interface{}) {
    6. if r.err == nil {
    7. r.err = binary.Read(r.r, binary.BigEndian, data)
    8. }
    9. }
    10. 调用:
    11. var p Point
    12. r := Reader{r: input}
    13. r.read(&p.Longitude)
    14. r.read(&p.Latitude)
    15. r.read(&p.Distance)
    16. r.read(&p.ElevationGain)
    17. r.read(&p.ElevationLoss)
    18. if r.err != nil {
    19. return nil, r.err
    20. }
    21. return &p, nil

    参考:https://coolshell.cn/articles/21140.html