Unlock Go's Syntactic Sugar: Master Variadic Functions and := Assignment
This article explains the concept of syntactic sugar in Go, illustrating how variadic parameters (using ...) and the short variable declaration operator := simplify code, with clear examples and important usage notes to improve readability and reduce errors.
Syntactic sugar, also called sugar-coated syntax, is a term coined by computer scientist Peter J. Landin to describe language features that do not add new functionality but make code easier to write and read.
1. Variadic parameters
In Go, three dots (
...) denote a variadic parameter, allowing a function to accept any number of arguments of the same type.
<code>func print(values ...string) { // can accept any number of string arguments
for _, v := range values {
fmt.Println("---> ", v)
}
}
func main() {
values := []string{"abc", "def", "hig", "klm"}
print(values...)
}
</code>Another example shows two ways to implement a variadic‑like function:
<code>func myFunc1(args ...int) {
for _, arg := range args {
fmt.Println(arg)
}
}
func myFunc2(args []int) {
for _, arg := range args {
fmt.Println(arg)
}
}
</code> myFunc1uses Go's syntactic sugar;
myFunc2achieves the same effect but requires the caller to construct a slice, making the call more verbose.
2. Assignment syntax sugar
The
:=operator combines declaration, assignment, and type inference in a single step.
<code>// First method
var number1, number2, number3 int
number1, number2, number3 = 1, 2, 3
// Second method
var number1, number2, number3 = 1, 2, 3
// Third method
number1, number2, number3 := 1, 2, 3
</code>Precautions
:= can be used only when at least one variable on the left side is newly defined.
:= performs only semantic checks; it can be used inside loops, behaving like
=after the first iteration.
Both := and = require the number of variables and values to match exactly; no truncation occurs.
Special cases: map, channel, and type assertions can return one or two values.
When a map key does not exist, the operation returns the zero value and
false; otherwise it returns
true.
When a channel is closed, receiving returns the zero value and
false; otherwise it returns
true.
Raymond Ops
Linux ops automation, cloud-native, Kubernetes, SRE, DevOps, Python, Golang and related tech discussions.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.