مرکزی مواد پر جائیں
eLearner.app
ماڈیول 3 · سبق 3 از 5کورس میں 13/50~10 min
ماڈیول اسباق (3/5)

متغیر افعال

Variadic functions accept an arbitrary number of arguments of the same type. You declare them by putting ... before the type of the last parameter. Inside the function the parameter is a slice.

Declaration

Go
func sum(nums ...int) int {
    tot := 0
    for _, n := range nums {
        tot += n
    }
    return tot
}

sum()              // 0   (nums = []int{})
sum(1)             // 1
sum(1, 2, 3, 4)    // 10

Only the last parameter can be variadic:

Go
func log(prefix string, values ...any) { ... }   // ok
// func wrong(...int, suffix string) {}            // ERRORE

Spreading a slice

If you already have a slice, you can pass it to a variadic function with ...:

Go
nums := []int{1, 2, 3}
sum(nums...)         // 6 — espande lo slice nei singoli argomenti

The "..." goes after the slice. Without spread you'd get a type error: you'd be passing a []int where the function expects a sequence of int.

nums is a slice, not a new container

Inside the function nums has type []int. All standard slice operations work: len(nums), nums[0], range, etc.

Classic use case: fmt.Println

All of fmt's Print* functions are variadic:

Go
// signature (semplificata):
// func Println(a ...any) (n int, err error)

fmt.Println("ciao", 42, true)
args := []any{"a", "b", "c"}
fmt.Println(args...)

Try it

ورزش#go.m3.l3.e1
کوششیں: 0لوڈ ہو رہا ہے…

Define sum(nums ...int) int that returns the sum of all arguments.

ایڈیٹر لوڈ ہو رہا ہے…
اشارہ دکھائیں۔

Inside the function `nums` has type `[]int`.

3 کوششوں کے بعد حل دستیاب ہے۔

ورزش#go.m3.l3.e2
کوششیں: 0لوڈ ہو رہا ہے…

Call the existing sum function by passing the slice nums with spread `nums...`.

ایڈیٹر لوڈ ہو رہا ہے…
اشارہ دکھائیں۔

The `...` goes AFTER the slice name.

3 کوششوں کے بعد حل دستیاب ہے۔

Quiz#go.m3.l3.e3
تیار

Inside `func f(args ...string)`, what type is `args`?

Go
func f(args ...string) {
    _ = args
}
جواب کے اختیارات

Recap

  • ...T as the LAST parameter = variadic function; inside it's []T.
  • Called with single values: the compiler collects them into a slice.
  • Called with an existing slice: slice... (spread, reuses the slice).
  • All fmt.Print* functions are variadic.
  • Only the last parameter can be variadic.