duanpang2751 2017-08-11 09:27
浏览 165
已采纳

gofmt换行保存

When formatting go source code with gofmt, it preserves the newlines so you can group items together. I'm interested on how this is actually implemented. I tried looking at the source code in the github repo golang/go, but couldn't find it immediately. If you look at https://github.com/golang/go/blob/master/src/go/printer/printer.go#L979:

// intersperse extra newlines if present in the source

How does the printer know those extra newlines are present in the source? Can someone point me into the right direction?

  • 写回答

3条回答 默认 最新

  • dongxian0421 2018-04-27 13:34
    关注

    gofmt works on the AST. When you look at https://golang.org/pkg/go/ast you'll see that every node has functions Pos() and End() which return the token.Pos of the beginning and end respectively. These are essentially offsets in the source file and as such know nothing about line numbers/breaks.

    But when combined with a token.Fileset such a token.Pos can be converted into a token.Position which includes the line number. gofmt does that in the function printer.go:lineFor().

    The actual insertion of linebreaks is done in nodes.go:linebreak(). The first argument to linebreak() is a line number obtained by calling the aforementioned lineFor() on the respective token.Pos. The function computes the difference between this line number and the line number of the last token that was printed (tracked in the pos field of struct printer). This tells it if the token to be printed now is on the same line in the input file as the previous token. If it isn't, that means the programmer included one or more line breaks in the original source and linebreak() will output at most 1 empty line. While it could preserve all input line breaks, gofmt's policy is to compress series of empty lines down to only 1 empty line.

    If the reason you're asking this question is that you want to customize gofmt, take a look at https://github.com/mbenkmann/goformat

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?