How to print the data in a frame using an array?

Viewed 42

I am trying to print the data in a frame using the olog library. When I use the string variables inside a struct and use them in the []Data{}, it prints the data in a frame but when I use the TicketHeading array in a struct and use it inside the []Data{}, it gives me the following error.

Error

go: finding module for package github.com/da0x/golang/olog
go: downloading github.com/da0x/golang v1.0.4
./prog.go:17:23: invalid field name dt.TicketHeading[0] in struct literal
./prog.go:18:23: invalid field name dt.TicketHeading[1] in struct literal

Code

package main

import "github.com/da0x/golang/olog"

type Data struct {
    TicketHeading [2]string
    Ticket_title, Ticket_description string
}

func main() {
    var dt Data
    dt.TicketHeading = [2]string{"Ticket_titles", "Ticket_descriptions"}
    var data = []Data{
        {dt.TicketHeading[0]: "This is the ticket heading"},
        {dt.TicketHeading[1]: "This is the ticket description"},
    }
    olog.Print(data)
}
2 Answers

The library you took initially does well the task it promises to do, as per its GitHub page https://github.com/da0x/olog

It takes any array of structs and assembles an ascii box around the objects

It prints structs only. In case you want to print some data loaded dynamically, from a file on instance, look at this library https://github.com/kataras/tablewriter. I guess the snippet below is a good fit for you:

package main

import (
    "os"
    "github.com/olekukonko/tablewriter"
)

func main() {
    data := [][]string{
        {"A", "The Good", "500"},
        {"B", "The Very very Bad Man", "288"},
        {"C", "The Ugly", "120"},
        {"D", "The Gopher", "800"},
    }

    table := tablewriter.NewWriter(os.Stdout)
    table.SetHeader([]string{"Name", "Sign", "Rating"})

    for _, v := range data {
        table.Append(v)
    }
    table.Render()
}

The library you use infers column names from names of data structure fields you provide, Data in this case. So to name columns like "Ticket_titles" and "Ticket_description" you just need to have fields with such names in your Data structure. No need to provide column names (header) separately as you did dt.TicketHeading = [2]string{"Ticket_titles", "Ticket_descriptions"}. Look at my example snippet below:

package main

// import "fmt"

import "github.com/da0x/golang/olog"

type Data struct {
    // TicketHeading                    [2]string
    Ticket_title, Ticket_description string
}

func main() {
    var data = []Data{
        {"Title 1", "Description 1"},
        {"Title 2", "Description 2"},
    }
    olog.Print(data)
}

It gives me this output:

> go run .
┌────────────┬──────────────────┐
│Ticket_title│Ticket_description│
├────────────┼──────────────────┤
│Title 1     │Description 1     │
│Title 2     │Description 2     │
└────────────┴──────────────────┘

You can refer to GitHub page for more details: https://github.com/da0x/olog

Related