简体   繁体   English

如何在Go中的Tabwriter中添加换行符?

[英]How to add a newline into tabwriter in go?

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, ' ', 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])
             }

How to add newline without affecting the format? 如何在不影响格式的情况下添加换行符?

As stated in the docs (emphasis is mine): 如文档中所述(重点是我的):

Tab-terminated cells in contiguous lines constitute a column. 连续行中以Tab键结尾的单元格构成一列。

https://golang.org/pkg/text/tabwriter/#Writer 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, "Replica\tStatus\tDataUpdateIndex\t\n")
fmt.Fprintf(q, "\t\t\t\n")  // blank line
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])
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM