Functions
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:
package main
func add(a int, b int) int {
return a + b
}
func main() {
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
package main
func main() {
println("Hello, World!")
}Functions can also return multiple values
package main
func swap(a, b int) (int, int) {
return b, a
}
func main() {
x, y := 1, 2
x, y = swap(x, y)
println(x, y) // Output: 2 1
}Functions can also have named return values
In Go, the function can also have variadic parameters, A variadic function can be called with any number of trailing arguments. For example
Last updated