Functions are reusable blocks of code that perform a specific task. They help organize programs into smaller units, improve code readability, and reduce duplication by allowing the same logic to be executed multiple times. Example:
package main
import "fmt"
func multiply(a, b int) int {
return a * b
}
func main() {
result := multiply(5, 10)
fmt.Println(result)
}
Output
50
Syntax
func functionName(parameters) returnType {
// function body
}
Components:
- func: Keyword used to declare a function.
- functionName: Name of the function.
- parameters: Input values accepted by the function.
- returnType: Data type returned by the function (optional).
Function Declaration
A function is declared using the func keyword, followed by the function name, parameters, and an optional return type.
Example:
func multiply(a, b int) int {
return a * b
}
Syntax
func function_name(Parameter-list)(Return_type) {
// function body...
}
Components:
- func: Keyword to declare a function.
- function_name: The name of the function, e.g.,
multiply. - Parameter-list:
a, b int—parameters with their types. - Return_type:
intspecifies the return type.
Function Calling
A function is executed by calling its name and passing the required arguments. The returned value can be stored in a variable or used directly.
Example
result := multiply(5, 10)
fmt.Printf("Result of multiplication: %d", result)
Explanation:
- multiply(5, 10) calls the function with 5 and 10 as arguments.
- The returned value is stored in result.
- fmt.Printf() displays the result.
Function Arguments
Function arguments are the values passed to a function when it is called. Go always passes arguments by value, meaning a copy of the argument is passed to the function. However, pointers can also be passed, allowing functions to modify the original variable indirectly.
Passing Arguments by Value
Go always passes arguments by value, meaning a copy of the variable is passed to the function. Any modifications made inside the function affect only the copied value and do not change the original variable.
package main
import "fmt"
func increment(num int) {
num++
fmt.Println("Inside function:", num)
}
func main() {
x := 5
fmt.Println("Before function call:", x)
increment(x)
fmt.Println("After function call:", x)
}
Output
Before function call: 5 Inside function: 6 After function call: 5
Explanation:
- increment() accepts an integer parameter num.
- When increment(x) is called, a copy of x is passed to the function.
- num++ modifies only the copied value.
- The original variable x remains unchanged after the function call.
Passing Pointers to Functions
Go always uses call by value, meaning a copy of the argument is passed to the function. However, pointers can be passed as arguments, allowing a function to modify the original variable indirectly.
package main
import "fmt"
func double(num *int) {
*num *= 2
}
func main() {
x := 5
fmt.Println("Before:", x)
double(&x)
fmt.Println("After:", x)
}
Output
Before: 5 After: 10
Explanation:
- double() accepts a pointer parameter *int.
- &x passes the memory address of x to the function.
- *num dereferences the pointer and accesses the original value.
- The statement *num *= 2 updates the original variable.
- Since the original value is modified, x becomes 10.
Note: Go does not support call by reference. All arguments are passed by value. When a pointer is passed to a function, Go creates a copy of the pointer itself, but both pointers still reference the same underlying variable.
Multiple Return Values
Unlike many programming languages, Go allows a function to return multiple values. This feature is commonly used to return a result along with additional information such as an error value.
Example: The following example returns both the quotient and remainder when dividing two numbers.
package main
import "fmt"
func divide(a, b int) (int, int) {
quotient := a / b
remainder := a % b
return quotient, remainder
}
func main() {
q, r := divide(10, 3)
fmt.Println("Quotient:", q)
fmt.Println("Remainder:", r)
}
Output
Quotient: 3 Remainder: 1
Explanation:
- divide() accepts two integer parameters a and b.
- quotient := a / b calculates the division result.
- remainder := a % b calculates the remainder.
- q, r := divide(10, 3) stores the returned values in two separate variables.
Variadic Functions
Variadic functions allow a function to accept a variable number of arguments of the same type. Instead of specifying a fixed number of parameters, the ... syntax is used.
Example: The following example calculates the sum of multiple numbers.
package main
import "fmt"
func sum(nums ...int) int {
total := 0
for _, value := range nums {
total += value
}
return total
}
func main() {
fmt.Println(sum(10, 20))
fmt.Println(sum(10, 20, 30, 40))
}
Output
30 100
Explanation:
- nums ...int allows the function to accept any number of integer arguments.
- Inside the function, nums behaves like a slice of integers.
- The for loop iterates through all the values.
- total accumulates the sum of all elements.
Difference Between Passing Values and Passing Pointers
| Aspect | Passing Values | Passing Pointers |
|---|---|---|
| What is passed | A copy of the value | A copy of the memory address (pointer) |
| Effect on original variable | Original variable remains unchanged | Original variable can be modified |
| Function call | function(x) | function(&x) |
| Common use | When data should not be modified | When the original value needs to be updated |
Note: Go always uses call by value. When passing pointers, Go passes a copy of the pointer, which still points to the original variable.