2

I'm using the UI lib (https://github.com/andlabs/ui) to make a program about students' groups.

The ui.SimpleGrid allows a "list" of Control to be entered:

func NewSimpleGrid(nPerRow int, controls ...Control) SimpleGrid

I feel like in Java and other languages, it worked just as an array, which basically means that giving it one would work. However, this appears not to be the same in Go.

func initStudentsGrid(students ...Student) ui.SimpleGrid {
var i int
var grd_studentsList []ui.Grid

for i = 0; i < len(students); i++ {
    grd_student := ui.NewGrid()

    grd_student.Add(ui.NewLabel(students[i].group), nil, ui.West, true, ui.LeftTop, true, ui.LeftTop, 1, 1)
    grd_student.Add(ui.NewLabel(students[i].lastName), nil, ui.West, true, ui.LeftTop, true, ui.LeftTop, 1, 1)
    grd_student.Add(ui.NewLabel(students[i].firstName), nil, ui.West, true, ui.LeftTop, true, ui.LeftTop, 1, 1)

    grd_studentsList = append(grd_studentsList, grd_student)
}

return ui.NewSimpleGrid(1, grd_studentsList)

The program's not compiling because:

cannot use grd_studentsList (type []ui.Grid) as type ui.Control in argument to ui.NewSimpleGrid: []ui.Grid does not implement ui.Control (missing ui.containerHide method)

Is there any way to do a kind of "cast" from an array to the required format, since it isn't possible to add the grids one by one (no append method on SimpleGrid)?

Razakhel
  • 732
  • 13
  • 34

2 Answers2

10

Try something like:

return ui.NewSimpleGrid(1, grd_studentsList...)
                                           ^^^^

This is mentioned in the spec Passing arguments to ... parameters.

cnicutar
  • 178,505
  • 25
  • 365
  • 392
  • Tanks for the tip, but it doesn't work either... (cannot use grd_studentsList (type []ui.Grid) as type []ui.Control in argument to ui.NewSimpleGrid) – Razakhel Mar 13 '15 at 13:20
  • So make `grd_studentsList` a `[]ui.Control`. Assuming the Grid type conforms to the interface, the rest of the code should work. – James Henstridge Mar 14 '15 at 01:21
4

It it doesn't work either...

cannot use grd_studentsList (type `[]ui.Grid`) as type `[]ui.Control`
in argument to `ui.NewSimpleGrid`

As I mentioned before ("What about memory layout means that []T cannot be converted to []interface{} in Go?"), you cannot convert implicitly A[] in []B.

You would need to copy first:

var controls []ui.Control = make([]ui.Control, len(grd_studentsList))
for i, gs := range grd_studentsList{
    controls [i] = gs
}

And then use the right slice (with the right type)

 return ui.NewSimpleGrid(1, controls...)
Community
  • 1
  • 1
VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250