dimanche 18 avril 2021

using variadic arguments to function in golang causes type error compared to passing non-variadically

I'm using the gui package for Go ImGui bindings, and I'm having trouble adding a variable number of variadic arguments to one of it's functions by passing in an array postpended with ... due to some type errors

My Code:

package main

import (
    "fmt"

    g "github.com/AllenDang/giu"
)

func handle(err error) {
    if err != nil {
        panic(err)
    }
}

var lines []g.Widget
func loop() {
    g.SingleWindow("hello world").Flags(g.WindowFlagsAlwaysAutoResize).Layout(
        lines...,
    )
}

func main() {
    imageSize := float32(150)
    lines = append(lines, *g.Line(
        g.ImageWithFile("/path/to/png").Size(imageSize, imageSize),
    ))

    wnd := g.NewMasterWindow("Hello world", 400, 200, g.MasterWindowFlagsTransparent, nil)
    wnd.Run(loop)
}

Compiling gets the following error

./main.go:105:16: cannot use *giu.Line(giu.ImageWithFile("/path/to/png").Size(imageSize, imageSize)) (type giu.LineWidget) as type giu.Widget in append:
        giu.LineWidget does not implement giu.Widget (Build method has pointer receiver)

OK, makes sense because g.Line() returns type *g.LineWidget and lines is of type []g.Widget. I change the global declaration of lines to...

var lines []g.LineWidget

It still won't compile...

./main.go:89:173: cannot use lines (type []giu.LineWidget) as type []giu.Widget in argument to giu.SingleWindow("hello world").Flags(giu.WindowFlagsNoTitleBar | giu.WindowFlagsNoResize | giu.WindowFlagsNoMove | giu.WindowFlagsNoCollapse | giu.WindowFlagsAlwaysAutoResize).Layout

Not sure why I am getting an error in this case, because if I pass in the parameter myself without using variadic expansion like so, it still works

g.SingleWindow("hello world").Flags(g.WindowFlagsNoTitleBar | g.WindowFlagsNoResize | g.WindowFlagsNoMove | g.WindowFlagsNoCollapse | g.WindowFlagsAlwaysAutoResize).Layout(
        g.Line(
            g.ImageWithFile("/path/to/png").Size(111, 111),
        ),
)

How do I remedy this? I tried using a function that took in ...interface{} and returned the proper type, and tweaked some other stuff, but none of that worked. Do I need to use reflection? I just want to pass in a variable number of parameters to that function at runtime, based on the images in a directory. Any help would be appreciated

Edit: Just a silly error, declaring lines like

var lines []g.Widget

and appending like

lines = append(lines, g.Line(
        // g.Button("Click Me").OnClick(onClickMe),
        g.ImageWithFile("/image").Size(imageSize, imageSize),
    ))

fixes the issue





Aucun commentaire:

Enregistrer un commentaire