How to add a newline into tabwriter in go?

huangapple go评论79阅读模式
英文:

How to add a newline into tabwriter in go?

问题

我想要打印一个换行符,但是如果我添加一个换行符,它会改变格式,以下是代码。

q := tabwriter.NewWriter(os.Stdout, 0, 0, 3, ' ', tabwriter.AlignRight|tabwriter.Debug)

fmt.Fprintf(q, "Replica\tStatus\tDataUpdateIndex\t\n")
fmt.Fprintf(q, "\n")
for i := 0; i < 4; i += 3 {
    fmt.Fprintf(q, "%s\t%s\t%s\t\n", statusArray[i], statusArray[i+1], statusArray[i+2])
}

如何在不影响格式的情况下添加换行符?

英文:

i want to print a newline but if i add a newline it changes the format, here is the code.

q := tabwriter.NewWriter(os.Stdout, 0, 0, 3, &#39; &#39;, tabwriter.AlignRight|tabwriter.Debug)

fmt.Fprintf(q, &quot;Replica\tStatus\tDataUpdateIndex\t\n&quot;)
fmt.Fprintf(q, &quot;\n&quot;)
for i := 0; i &lt; 4; i += 3 {
    fmt.Fprintf(q, &quot;%s\t%s\t%s\t\n&quot;, statusArray[i], statusArray[i+1], statusArray[i+2])
             }

How to add newline without affecting the format?

答案1

得分: 2

根据文档所述(重点是我的):

> 连续行中以制表符结尾的单元格构成一列。

https://golang.org/pkg/text/tabwriter/#Writer

当你在代码中插入新行时,你将标题行和内容行分开,所以它们不被视为“列”。

为了修复这个问题,让你的换行插入一个具有相同列数的空行。

fmt.Fprintf(q, "Replica\tStatus\tDataUpdateIndex\t\n")
fmt.Fprintf(q, "\t\t\t\n")  // 空行
for i := 0; i < 4; i += 3 {
    fmt.Fprintf(q, "%s\t%s\t%s\t\n", statusArray[i], statusArray[i+1], statusArray[i+2])
}
英文:

As stated in the docs (emphasis is mine):

> Tab-terminated cells in contiguous lines constitute a column.

https://golang.org/pkg/text/tabwriter/#Writer

When you insert the new line in your code, you are separating the header and content lines so they are not treated as "columns".

In order to fix that, make your newline insert an empty row with the same number of columns (but blank).

fmt.Fprintf(q, &quot;Replica\tStatus\tDataUpdateIndex\t\n&quot;)
fmt.Fprintf(q, &quot;\t\t\t\n&quot;)  // blank line
for i := 0; i &lt; 4; i += 3 {
    fmt.Fprintf(q, &quot;%s\t%s\t%s\t\n&quot;, statusArray[i], statusArray[i+1], statusArray[i+2])
}

huangapple
  • 本文由 发表于 2017年7月21日 20:19:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/45237529.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定