← Fundamentals
Fundamentals

Optional, default, and variadic parameters

How does one function accept different numbers of arguments, and what does it receive when some are left out?

Flexible call interfaces must preserve missing options and the boundary between a list and its elements.

Outcome

Predict what a rest, variadic or optional parameter receives for each call, tell “not given” apart from a zero value, and pass a list on as separate arguments when the callee expects them.

Terminology (5)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

Variadic parameter
An interface accepting a variable number of trailing arguments; arrays, slices and compile-time packs represent them differently.
Default value
A value used for a parameter when the caller leaves the argument out.
Not given
A call that leaves an optional value out, as opposed to passing 0 or an empty value.
Spreading
Passing a list’s elements as separate arguments rather than the list as one.
Variadic slice
Go’s ...T parameter, a slice inside the function; s... passes an existing slice.

Optional inputs and variable argument lists

A Go variadic parameter receives trailing arguments as a slice. At the call site, the trailing ... form passes a matching slice as the variadic argument list. That interface differs from passing a slice value as one argument.

Go has no default parameters. A helper needs an explicit representation and policy for an omitted option. Decide how presence is recorded before applying a fallback, then preserve the distinction between fixed arguments and a variable payload when forwarding a call.

01Any number of values

A call with no extra values is a normal call

A match-report worker accepts a variable-length score submission for each player. After preparing a summary, it needs a delivery-job attempt option and an ordered batch of channel notices. Those inputs arrive as lists and optional fields; the worker must preserve what the caller supplied as it builds its report.

A submitted score list can have several entries or no entries yet. Before computing the player summary, isolate that empty-list boundary with total, which adds the supplied points. It receives three values, no values, and a two-value list. Predict the second line.

total has a variadic parameter, points ...int; the last call passes a slice with extra....

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
package main

import "fmt"

func total(points ...int) int {
	sum := 0

	for _, point := range points {
		sum += point
	}

	return sum
}

func main() {
	extra := []int{4, 3}

	fmt.Println(total(12, 9, 15))
	fmt.Println(total())
	fmt.Println(total(extra...))
}
What does total print for the call with no values?
Go · terminal.sh
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
go run .

Use the selected language’s setup from the first reading and replace the file for each experiment. Scores and attempt counts are supplied small nonnegative whole numbers. Messages are single input words. The programs print the summary and dispatch report for these valid inputs.

02Left out versus zero

Resolve the job’s attempt option

The worker’s policy allows 3 attempts when a job omits its count; a supplied zero disables attempts. Compare how each shown interface represents that option. Predict the call that supplies zero.

Go has no default parameters. This probe uses an int parameter and an explicit branch in the body.

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
package main

import "fmt"

// 0 stands for "not given", so the default can be applied.

func attempts(count int) int {
	if count == 0 {
		return 3
	}

	return count
}

func main() {
	fmt.Println(attempts(5))
	fmt.Println(attempts(0))
}
What does the call that passes 0 print?

03Passing a list on

Forward the prepared notice batch

The notice stage already holds its messages in a list. To inspect the next call boundary without printing the messages, count reports how many arguments it receives. Compare a direct call with the call through that prepared list.

forward collects items ...any, then calls count(items).

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
package main

import "fmt"

func count(items ...any) int {
	return len(items)
}

func forward(items ...any) int {
	return count(items)
}

func main() {
	fmt.Println(count("a", "b", "c"))
	fmt.Println(forward("a", "b", "c"))
}
What do the two lines print?

04Repair the match-report worker

Summaries, retry options, then ordered notices

The worker has three small entry points used by the same report delivery flow. First summarize a player’s submitted scores, including an empty submission. Then resolve each queued job’s attempt option, keeping an explicit opt-out of 0. Finally forward a batch to the existing send helper so the channel receives one notice per message, followed by an accurate sent count.

The shown fixtures include omitted options, explicit zero and positive counts, empty message batches and several messages. These distinguish missing configuration from a deliberate value and a message batch from one list-shaped message.

Repair the match-report worker

The empty call, the difference between left out and zero, then a list passed on as separate arguments.

  1. easy · F-VARIADIC-V4-1 Score players with no scores
  2. medium · F-VARIADIC-V4-2 Keep an explicit zero
  3. hard · F-VARIADIC-V4-3 Forward each message
In the frontend An omitted component prop and an explicit zero carry different retry choices. Optional

The worker’s review panel displays a job’s maximum attempt count. Its component defaults that prop to 3, while a supplied 0 keeps the action disabled. These static examples show the same presence distinction at a component boundary.

Example.tsx
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
type Props = { maxAttempts?: number };

export default function AttemptPreview({ maxAttempts = 3 }: Props) {
  return (
    <button disabled={maxAttempts === 0}>Plan up to {maxAttempts} attempts</button>
  );
}

The destructured prop initializer supplies 3 when maxAttempts is omitted or undefined. An explicit 0 remains 0, so the disabled expression is true. A parent expression such as value || 3 would replace zero before this component receives it. The prop contract here is an optional nonnegative whole count, without null.

Sources: React: default prop values,Svelte: fallback values in $props.

Sources

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.