gizak / termui

Golang terminal dashboard
MIT License
13.23k stars 786 forks source link

Question: Grid Error #224

Closed keithknott26 closed 5 years ago

keithknott26 commented 5 years ago

Hello,

This should probably be tagged as a question instead of as a bug, I'm trying to follow your examples from goTop and using the following code snippet (some bits are stripped out) I'm getting the following error when rendering the grid.

var (
    grid  *ui.Grid
    plot0 *w.Plot
    par0  *w.Paragraph
)

func initWidgets() {
    plot0 = w.NewPlot()
    par0 = w.NewParagraph()
}
func setupGrid() {
    grid := ui.NewGrid()
    termWidth, termHeight := ui.TerminalDimensions()
    grid.SetRect(0, 0, termWidth, termHeight)
    plotRow := ui.NewRow(1.0/1,
        ui.NewCol(1.0/6, par0),
        ui.NewCol(5.0/6, plot0),
    )
    grid.Set(plotRow)
}
func main() {
                if err := ui.Init(); err != nil {
            log.Fatalf("failed to initialize termui: %v", err)
        }
        defer ui.Close()
           initWidgets()
               setupGrid()
...
          ui.Render(grid)
}

[5/5]0xc0000ac3c0[5/5]0xc0000ac370panic: runtime error: invalid memory address or nil pointer dereference [signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x1115845]

goroutine 1 [running]: github.com/gizak/termui.(*Grid).GetRect(0x0, 0x0, 0x6, 0xffffffffffffffff, 0x0)

:1 +0x5 github.com/gizak/termui.Render(0xc0000bbc20, 0x3, 0x3) /Users/keithknott/go/src/github.com/gizak/termui/render.go:21 +0x189 main.main() /Users/keithknott/go/src/github.com/keithknott26/linegraph/linegraph.go:266 +0xd99 Any idea why this happens? Perhaps I'm defining the grid incorrectly? The same code works fine when I move it back into main()
cjbassi commented 5 years ago

So the issue is with this line:

grid := ui.NewGrid()

which should be changed to

grid = ui.NewGrid()

with the colon removed. Instead of assigning to the global grid variable, you're creating a new local grid, so the global grid stays nil. Definitely one of the gotchas with Go. :)

Let me know if you have any other questions.