How to use function with any number of arguments (variadic functions) in Go

2 Answers

0 votes
package main
   
import (
    "fmt"
)

func add(numbers ...int) {
	fmt.Print(numbers, " ")
    sum := 0
    for _, n := range numbers {
        sum += n
    }
    fmt.Println(sum)
}
   
func main() {
    add(12, 767, -9)
	add(1, 2, 3, 4)
	
	arr := []int{1, 2, 3, 4, 5}
	add(arr...)
}   
   
   
   
/*
run:
   
[12 767 -9] 770
[1 2 3 4] 10
[1 2 3 4 5] 15

*/

 



answered Feb 23, 2020 by avibootz
0 votes
package main

import (  
    "fmt"
)

func f(n int, numbers ...int) {  
    for i, val := range numbers {
        if val == n {
            fmt.Println(val, "found at index", i, ":", numbers)
        }
    }
}
func main() {  
    f(2, 1, 2, 8)
    f(3, 17, 18, 4, 56, 3, 5, 7)
    f(9, 12, 13, 1, 4)
    f(100)
}
  
  
/*
run:
  
2 found at index 1 : [1 2 8]
3 found at index 4 : [17 18 4 56 3 5 7]
 
*/

 



answered Feb 24, 2020 by avibootz

Related questions

1 answer 170 views
1 answer 57 views
2 answers 255 views
...