A function in Go is a reusable and organized block of code that performs a specific operation. Functions allow you to modularize your code, making it more maintainable, reusable, and testable. In Go, functions can be defined with a set of input parameters, a return type, and a function body.
To declare a function in Go, you use the ‘func‘ keyword, followed by the function name, a parameter list enclosed in parentheses, an optional return type, and a function body enclosed in curly braces ‘‘. Here’s the general syntax for a function declaration in Go:
func functionName(parameterList) returnType {
// function body
}
The ‘parameterList‘ is a comma-separated list of parameters with their data types, and the ‘returnType‘ can be a single type or a tuple of types enclosed in parentheses.
Here’s an example of a simple function that takes two integers as input parameters and returns their sum:
func add(a int, b int) int {
return a + b
}
In this example, the function ‘add‘ takes two input parameters ‘a‘ and ‘b‘ of type ‘int‘ and returns an ‘int‘ value.
You can also return multiple values from a function by specifying them as a tuple in the return type:
func divmod(a int, b int) (int, int) {
quotient := a / b
remainder := a % b
return quotient, remainder
}
In this example, the function ‘divmod‘ takes two input parameters ‘a‘ and ‘b‘ of type ‘int‘ and returns a tuple containing two ‘int‘ values – the quotient and the remainder of the division.
To use a function in your code, you simply call it by its name, passing the required arguments, and you can assign the return value(s) to one or more variables if needed:
func main() {
sum := add(3, 5)
q, r := divmod(10, 3)
}
In summary, functions in Go provide a way to encapsulate a block of code to perform a specific task. They can be declared with the ‘func‘ keyword, followed by the function name, a parameter list, an optional return type, and a function body. Functions help make your code more modular, maintainable, and reusable.