Arguments
Go functions of course can also take arguments:
func add(x int, y int) int { return x + y}
Similar to variables that share the same type, you can use a shorthand to define function arguments of the same type:
func add(x, y int) int { return x + y}
However, there are quite some differences between Go and JavaScript/TypeScript when it comes to function arguments:
Variadic Parameters
Section titled “Variadic Parameters”Go allows you to pass a variable number of arguments to a function using the ...
syntax:
func sum(numbers ...int) int { total := 0 for _, number := range numbers { total += number } return total}
Usage:
func main() { result := sum(1, 2, 3, 4, 5) fmt.Println(result) // Output: 15}
Or if you have a slice of integers, you can “spread” them as well:
func main() { numbers := []int{1, 2, 3, 4, 5} result := sum(numbers...) fmt.Println(result) // Output: 15}
Note that unlike JavaScript/TypeScript the “spread” ...
is added to the end of the “sliced” var.