Golang - How to "convert" an array ( [ ] ) to a list ( ... )?

Razakhel :

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)?

VonC :

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...)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related