Print out some struct fields as tabular format

I’m trying to get help on what’s the recommended way of doing the following.

I want to print out selective fields in a struct slice as nice tabular interface. The data I get from HTTP call is in struct slice type and the response may have 10 fields for the struct but I only need to print out several related fields as tabular ascii format for users to see.

For example, the data may contain 100 networks, each network has 10 fields like network name, field, vlan… but I only want to use 3 fields and print out a nice tabular output so users can see name, vlan number for all 100 networks.

I’m looking at tablewriter library but it looks like it wants a two dimensional string slice as input.

If tablewriter is a good way going forward, what’s the recommended way to append selected struct fields to a two-dimensional string slice.

Or there are other better options?

Thanks
Hongjun

The simplest way (to me) would be to loop over your data and use the tabwriter from the standard library. Essentially (typing on the phone…):

tw := tabwriter.NewWriter(...)
for _,v := values {
  fmt.Fprintf(tw, "%v\t%v\t%v\n", v.IP, v.VLAN, v.Notes)
}
tw.Flush()

Regular printf with fixed field widths can also work nicely. At least things like IP prefixes and VLAN numbers have known max lengths.

Don’t look for a functional-like operation to map, extract and zip your slice into some other two dimensional slice without looping. It’s not how go does it.

2 Likes

Thanks. That works well. I put range before values to iterate the slice.

Could you elaborate more on “It’s not how go does it.”?

I was using tablewriter library and used append func to add individual row to the 2D slice and then get it printed out.

network_table := [][]string{}
for _, v := range values {
		row := []string{v.IP, v.VLAN, v.Notes}
		network_table = append(network_table, row)
}

That’s perfectly fine as well. I was just trying to say that the recommended way to append something to a slice is to use a loop.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.