dsfsad089111 2015-03-13 11:56
浏览 1201
已采纳

Golang-如何将数组([])“转换”为列表(…)?

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

  • 写回答

2条回答 默认 最新

  • dounielong7728 2015-03-13 15:08
    关注

    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...)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥20 求用stm32f103c6t6在lcd1206上显示Door is open和password:
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法