如何遍历一个列表并使用goterm包绘制表格?

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

How to iterate over a list and draw a table with the goterm package?

问题

我正在尝试使用goterm进行快速原型设计。我有一个包含用户对象的结构体列表。我想输出一个标题行(可以正常工作),然后迭代列表(可以正常工作),并为每个用户添加一行。然而,使用下面的代码,控制台上没有任何输出。没有空行。什么都没有。程序只是返回了。我已经成功地使用链接的示例来显示标题行和数据行。但是,按照我现在的迭代方式添加到表格中并没有起作用。我确定我漏掉了一些非常基本的东西。希望能得到帮助。我会继续努力解决问题。

func usersListOutputConsole(users *data.UserList) {
  userTable := tm.NewTable(0, 10, 5, ' ', 0)
  fmt.Fprintf(userTable, "ID\tName\tFull Name\tEmail\n") // 标题行
  for _, user := range users.Data {
    fmt.Fprintf(userTable, "%d\t%s\t%s\t%s\n", user.ID, user.Attributes["name"], user.Attributes["full_name"], user.Attributes["email"])
  }
  tm.Println(userTable)
  tm.Flush()
}
英文:

I am trying to rapidly prototype something with goterm. I have a list of user objects in a struct. I want to output a header row (works) then iterate over the list (works) and add a row for each user. However, with the code below, nothing renders to the console. No blank lines. Nothing. The program just returns. I have gotten the linked example to work with just the header row and a data row. Appending to the table by iterating as I am is not working. I am certain I am missing something very basic. Help would be appreciated. I will continue hacking away.

func usersListOutputConsole(users *data.UserList) {
  userTable := tm.NewTable(0, 10, 5, ' ', 0)
  fmt.Fprintf(userTable, "ID\tName\tFull Name\tEmail\n") // the header row
  for _, user := range users.Data {
    fmt.Fprintf(userTable, "%d\t%s\t%s\t%s\n", user.ID,   user.Attributes["name"], user.Attributes["full_name"], user.Attributes["email"])
  }
  tm.Println(userTable)
  tm.Flush()
}

答案1

得分: 0

经过进一步测试,我发现一切实际上都正常工作。我在goterm和Go的本地tabwriter之间的差异中没有注意到的是,前者更像一个实际的终端程序,并重新绘制屏幕。令人尴尬的是,由于期望有滚动输出,我的终端窗口对于输出的50多行来说太小了。在意识到这一点并发现我想要tabwriter的滚动输出后,我切换了一下,几分钟后一切都按预期工作了。如果你正在寻找一个类似交互式终端程序的话,goterm是一个很棒的包。但这不是我想要的,尽管我之前被它的格式化能力所吸引。简而言之,RTFM。

英文:

After some more testing I found that everything was, in fact, working properly. What I had failed to catch in the differences between goterm and Go's native tabwriter is that the former is more of an actual terminal program and redraws the screen. Embarrassingly, expecting scrolling output, my terminal window was too small for the 50+ rows being output. After realizing this and finding that I wanted the scrolling output of tabwriter, I switched and minutes later everything was working as expected. goterm is a fantastic package if you're looking for an interactive-like terminal program. It's not what I wanted though I had been attracted to it for its formatting capabilities. In short, RTFM.

huangapple
  • 本文由 发表于 2016年1月22日 23:01:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/34949685.html
匿名

发表评论

匿名网友

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

确定