英文:
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, ' ', 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?
答案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, "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])
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论