Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Prodentim Probiotics Specially Designed For The Health Of Your Teeth And Gums

Instant Grammar Checker - Correct all grammar errors and enhance your writing

Teach Your Child To Read

Powerful WordPress hosting for WordPress professionals

Disclosure: My content contains affiliate links.

31,167 questions

40,724 answers

573 users

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

Freaking Awesome WordPress Hosting
184 views
asked Feb 23, 2020 by avibootz
edited Feb 27, 2020 by avibootz

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 89 views
1 answer 30 views
30 views asked Jun 9, 2023 by avibootz
...