In programming, a function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing. Go, like many other programming languages, supports functions as first-class citizens, allowing you to define them, call them, and pass them around just like any other variable.
In this tutorial, we'll cover how to define and call functions in Go. We'll also explore some practical examples to help solidify your understanding.
A function in Go is defined using the func keyword followed by the function name, parameters (if any), return types (if any), and the body of the function enclosed in curly braces {}.
Here's the basic syntax for defining a function:
func functionName(parameters) returnType {
// Function body
}
- **functionName**: The name of the function.
- **parameters**: A list of input parameters that the function takes. Each parameter has a type.
- **returnType**: The type of value that the function returns. If the function doesn't return anything, you can omit this part or use `void` (though Go uses `()` for no return).
- **Function body**: The code block where the actual computation happens.
## Examples
### Example 1: Simple Function
Let's start with a simple example of a function that adds two integers and returns their sum.
```go
func add(a int, b int) int {
return a + b
}
In this example:
- `add` is the name of the function.
- It takes two parameters, `a` and `b`, both of type `int`.
- It returns an `int`.
To call this function, you can do the following:
```go
func main() {
result := add(3, 4)
fmt.Println(result) // Output: 7
}
### Example 2: Function with No Return Value
Sometimes, a function might perform an action but not return any value. In such cases, you can define the function without specifying a return type.
```go
func greet(name string) {
fmt.Printf("Hello, %s!\n", name)
}
To call this function:
func main() {
greet("Alice") // Output: Hello, Alice!
}
Go allows functions to return multiple values. This is often used for error handling or returning multiple results from a single computation.
func divide(a int, b int) (int, error) {
if b == 0 {
return 0, errors.New("division by zero")
}
return a / b, nil
}
To call this function:
func main() {
result, err := divide(10, 2)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(result) // Output: 5
}
_, err = divide(10, 0)
if err != nil {
fmt.Println(err) // Output: division by zero
}
}
Go also supports named return values. This can make the code more readable and concise.
func multiply(a int, b int) (product int) {
product = a * b
return
}
To call this function:
func main() {
result := multiply(3, 4)
fmt.Println(result) // Output: 12
}
In the next section, we'll dive deeper into functions by exploring how to use parameters effectively. We'll cover different types of parameters, including variadic parameters and named parameters.
Stay tuned!