Search code examples
govariadic-functions

variadic function, cannot pass parameters


To call a dialog executable, which expects up to 3 buttons, I created this function:

func Dialog(icon string, text string, buttons ...string) int {
    cmd := &exec.Cmd{
        Path: dialogPath,
        Args: []string{
            dialogPath,
            icon,
            text,
            buttons...,
        },
        Stdout: os.Stdout,
        Stdin:  os.Stdin,
    }
    var waitStatus syscall.WaitStatus
    if err := cmd.Run(); err != nil {
        if exitError, ok := err.(*exec.ExitError); ok {
            waitStatus = exitError.Sys().(syscall.WaitStatus)
            return waitStatus.ExitStatus()
        }
    }
    return 0
}

The issue is: This doesn't even compile because I do not understand how to pass the buttons to the Cmd. I thought unpacking would do the trick.


Solution

  • The error is:

    syntax error: unexpected ..., expecting comma or }
    

    This is because this is not valid syntax:

        Args: []string{
            dialogPath,
            icon,
            text,
            buttons...,
        },
    

    You can only use ... in function calls; you can use append() to work around this:

        Args:   append([]string{dialogPath, icon, text}, buttons...),