The efficient way to print a table in GO

Viewed 13320

I would like to know a simple and efficient way to print a table in Go. The solution I found works but it is really ugly.

many Thanks !

outfile := "file.tsv"
f, err := os.Create(outfile)
var buffer bytes.Buffer

buffer.WriteString(a[i])
buffer.WriteString("\t")
buffer.WriteString(a[j])
buffer.WriteString("\t")
buffer.WriteString(strconv.FormatFloat(x, 'f', 4, 64))
buffer.WriteString("\n")
// // write results to outfile
f.WriteString(buffer.String()) 
2 Answers

The tabwriter package in the standard library is simple and easy for this kind of thing:

w := tabwriter.NewWriter(os.Stdout, 1, 1, 1, ' ', 0)
fmt.Fprintln(w, "a\tb\tc\td\t")
fmt.Fprintln(w, "aa\tbb\tcc\t")
fmt.Fprintln(w, "aaa\tbbb\tccc\t")
fmt.Fprintln(w, "aaaa\tbbbb\tcccc\tdddd\t")
w.Flush()

// Prints out:
// a    b    c    d 
// aa   bb   cc   
// aaa  bbb  ccc  
// aaaa bbbb cccc dddd 

You can replace the os.Stdout with any io.Writer.

Related