英文:
ellipsis expansion fyne NewVBox
问题
我正在尝试创建一个包含一系列按钮的Fyne垂直框,但无法弄清楚基本的机制。我认为这是一个关于Go语言的问题,而不是Fyne的问题,关于Go语言的某些东西我不太理解。
这是一个最简程序,展示了我的意思:
package main
import (
"fmt"
"fyne.io/fyne/v2/app"
"fyne.io/fyne/v2/container"
"fyne.io/fyne/v2/widget"
)
func main() {
a := app.New()
w := a.NewWindow("Button List")
btn0 := widget.NewButton("button 0", func() {
fmt.Println("Pressed 0")
})
btn1 := widget.NewButton("button 1", func() {
fmt.Println("Pressed 1")
})
btns := []*widget.Button{btn0, btn1}
vbox := container.NewVBox(
// does work
btns[0],
btns[1],
// doesn't work
// btns...,
)
w.SetContent(
vbox,
)
w.ShowAndRun()
}
我理解的是,参数btns...
应该产生与参数列表btn[0],btn[1]
相同的效果,但显然并不是这样。如果我注释掉以下行:
btn[0],
btn[1],
并取消注释以下行:
btns...
我会得到错误消息:
cannot use btns (type []*"fyne.io/fyne/v2/widget".Button) as type
[]fyne.CanvasObject in argument to container.NewVBox
所以,我的新手问题是:
- 这里发生了什么,即为什么
btns...
不起作用? - 作为
NewVBox
的参数,我应该使用什么?
英文:
I'm trying to create a Fyne vertical box with a series of buttons but can't figure out the basic mechanism. I think this is a Go question, not a Fyne question, something I don't understand about go.
Here is a minimal program to show what I mean:
package main
import (
"fmt"
"fyne.io/fyne/v2/app"
"fyne.io/fyne/v2/container"
"fyne.io/fyne/v2/widget"
)
func main() {
a := app.New()
w := a.NewWindow("Button List")
btn0 := widget.NewButton("button 0", func() {
fmt.Println("Pressed 0")
})
btn1 := widget.NewButton("button 1", func() {
fmt.Println("Pressed 1")
})
btns := []*widget.Button{btn0, btn1}
vbox := container.NewVBox(
// does work
btns[0],
btns[1],
// doesn't work
// btns...,
)
w.SetContent(
vbox,
)
w.ShowAndRun()
}
My understanding is that the argument btns...
should produce the same effect as the list of arguments btn[0], btn[1]
, but it apparently doesn't. If I comment out the lines
btn[0],
btn[1],
and uncomment the line
btns...
I get the error message
> cannot use btns (type []*"fyne.io/fyne/v2/widget".Button) as type
> []fyne.CanvasObject in argument to container.NewVBox
So, my newbie questions:
- whats going on here, i.e., why doesn't
btns...
work? - what should I be using as the argument to
NewVBox
instead?
答案1
得分: 4
要实现你想要的效果,你需要修改*widget.Button
的切片,使其成为[fyne.CanvasObject](https://pkg.go.dev/fyne.io/fyne/v2@v2.1.0#CanvasObject)
的切片。
当将参数展开到可变参数中时,类型必须与可变参数期望的类型完全匹配。这意味着类型必须是接口本身,而不是实现接口的类型。
在你的情况下,以下代码将起作用:
btns := []fyne.CanvasObject{btn0, btn1}
vbox := container.NewVBox(btns...)
英文:
To do what you're wanting to do here you need to modify the slice of *widget.Button
to be a slice of fyne.CanvasObject.
When spreading into a variadic parameter like this, the types have to match exactly to what the variadic parameter is expecting. This means the type needs to be the interface itself and not a type that implements the interface.
In your case, the following will work:
btns := []fyne.CanvasObject{btn0, btn1}
vbox := container.NewVBox(btns...)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论