liveBook · Manning

Variadic arguments

As explained in Go by Example

A variadic function is a function that accepts a variable number of arguments through a variadic parameter represented inside the function as a slice.

A variadic function accepts an arbitrary number of values of the same type. With `func testRun(args ...string)`, callers provide separate strings, while the function receives `args` as a `[]string`. section 5.4.3 section 5.6

A convenient CLI test helper

A test helper can accept command-line arguments directly: `testRun("-c=2", "-n=1")`. Inside the helper, prepend the program name with `append([]string{"hit"}, args...)`, producing the argument list expected by the command runner. This keeps tests concise while returning the test environment and any execution error. section 5.4.3 section 5.4

Use either of these call forms:

  • Pass values individually: `testRun("-c=2", "-n=1", "https://github.com/inancgumus")`. section 5.4.3
  • Expand an existing slice with `...`: `testRun([]string{"-c=2", "-n=1"}...)`. section 5.4.3
  • Copy a slice before expansion when the helper might modify its elements: `testRun(append([]string{}, args...)...)`. section 5.4.3
Listing 5.6 Test runner helper (hit/cmd/hit_test.go)
func testRun(args ...string) (*testEnv, error) {  #1
    var tenv testEnv  #2
    err := run(&env{  #3
        args:   append([]string{"hit"}, args...),  #4
        stdout: &tenv.stdout,  #5
        stderr: &tenv.stderr,   #5
        dryRun: true,  #6
    })
    return &tenv, err  #7
}

Inspect the complete test runner helper, including variadic declaration, argument construction, dry-run configuration, and returned results. section 5.4.3

How Go by Example covers it

How deep it goes
Explains declarations, individual calls, slice expansion, local slices, and copying before modification.
Examples
Uses the `testRun` CLI helper, expanded argument slices, and prepended `hit` command arguments.
What you can do after
Apply it by writing helpers that accept separate values or expanded slices and pass those values into testable command execution.
How it connects
Connects variadic arguments to slices, append, command-line arguments, testing, and dependency injection.

Also explained in

Compare how 8 books explain variadic arguments →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go by Example. The section links point to the parts of the book it draws on.