Search code examples
goslicevariadic

Call a variadic function in Go


I have code where I am calling filepath.Join as described in the following program. However, I see an error

Program:

package main

import (
    "fmt"
    "path/filepath"
)

func main() {
    myVal := joinPath("dir1", "dir2")
    fmt.Println(myVal)
}

func joinPath(dirs ...string) string {
    return filepath.Join("mydir", dirs...)
}

Error: ./prog.go:16:32: too many arguments in call to filepath.Join have (string, []string) want (...string)

While I know this is a legitimate error, how do I join the path with a default parent directory using Join


Solution

  • You can't mix a slice and explicit elements for a variadic parameter, for details, see mixing "exploded" slices and regular parameters in variadic functions

    However, in your special case you may call filepath.Join() twice, and get the same result:

    func joinPath(dirs ...string) string {
        return filepath.Join("mydir", filepath.Join(dirs...))
    }
    

    You may also prepare a slice with all elements, and pass that like this:

    func joinPath(dirs ...string) string {
        return filepath.Join(append([]string{"mydir"}, dirs...)...)
    }
    

    Both will return and output (try them on the Go Playground):

    mydir/dir1/dir2