Unlock Go’s Hidden Power: How Syntactic Sugar Simplifies Your Code
This article explains Go's syntactic sugar—such as variadic parameters and the := assignment operator—showing how these language shortcuts improve readability, reduce boilerplate, and help developers write clearer, more maintainable code.
Syntactic sugar, coined by Peter J. Landin, refers to language syntax that does not add new functionality but makes code easier to write and read, thereby reducing errors.
1. Variadic parameters
In Go, the ellipsis ... after a parameter type denotes a variadic function, allowing any number of arguments of the same type.
func print(values ...string) {
for _, v := range values {
fmt.Println("--- > ", v)
}
}
...
values := []string{"abc", "def", "hig", "klm"}
print(values...)Another example compares a true variadic function with a slice‑based alternative:
func myFunc1(args ...int) {
for _, arg := range args {
fmt.Println(arg)
}
}
func myFunc2(args []int) {
for _, arg := range args {
fmt.Println(arg)
}
}
myFunc1(2, 3, 4) // simple call
myFunc2([]int{2, 3, 4}) // requires slice construction2. Assignment and declaration sugar
The := operator combines variable declaration, assignment, and type inference.
// three ways to assign three integers
var number1, number2, number3 int
number1, number2, number3 = 1, 2, 3
var number1, number2, number3 = 1, 2, 3
number1, number2, number3 := 1, 2, 3Precautions
:=can be used only when at least one variable on the left side is new.
It performs only a semantic check; inside loops it behaves like = after the first use.
Both := and = require the number of variables and values to match.
Special cases: map, chan, and type‑inferred functions may return one or two values.
When a map key is absent, the lookup returns the zero value and false.
When a closed channel is read, it returns the zero value and false.
Source: https://www.cnblogs.com/malukang/p/12955983.html
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
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.
