In Go, a function is a block of code that performs a specific task and returns a result. Functions can take zero or more input parameters and can return zero or more output values.
Here is an example of a simple function that takes two integers as input parameters and returns their sum:
packagemainfuncadd(a int, b int) int {return a + b}funcmain() { result := add(3, 4)println(result) // Output: 7}
Another example of a function is the main the function which is the entry point of the program
packagemainfuncmain() {println("Hello, World!")}
Functions can also return multiple values
packagemainfuncswap(a, b int) (int, int) {return b, a}funcmain() { x, y :=1, 2 x, y = swap(x, y)println(x, y) // Output: 2 1}
Functions can also have named return values
packagemainfuncsplit(sum int) (x, y int) { x = sum *4/9 y = sum - xreturn}funcmain() { fmt.Println(split(17)) // "4 13"}
In Go, the function can also have variadic parameters, A variadic function can be called with any number of trailing arguments. For example
packagemainimport"fmt"funcadd(args ...int) int { total :=0for _, v :=range args { total += v }return total}funcmain() { fmt.Println(add(1, 2, 3)) // 6 fmt.Println(add(1, 2, 3, 4)) // 10}