![]() |
VOOZH | about |
In Go, functions are blocks of code that perform specific tasks, which can be reused throughout the program to save memory, improve readability, and save time. Functions may or may not return a value to the caller.
multiplication: 50
func function_name(Parameter-list)(Return_type) {
// function body...
}
Table of Content
In Go, a function is declared with the func keyword, followed by its name, parameters, and optional return type.
func function_name(Parameter-list)(Return_type) {
// function body...
}
For our multiply example:
func multiply(a, b int) int {
return a * b
}
multiply.a, b int—parameters with their types.int specifies the return type.To use a function, simply call it by its name with any necessary arguments. Here, multiply(5, 10) calls the function with 5 and 10 as arguments.
Example
result := multiply(5, 10)
fmt.Printf("Result of multiplication: %d", result)
Go supports two ways to pass arguments to functions: Call by Value and Call by Reference. By default, Go uses call by value, meaning values are copied, and changes inside the function do not affect the caller’s variables.
In call by value, values of the arguments are copied to the function parameters, so changes in the function do not affect the original variables.
Example:
Before: x = 5, y = 10 multiplication: 100 After: x = 5, y = 10
In call by reference, pointers are used so that changes inside the function reflect in the caller’s variables.
Example:
Before: x = 5, y = 10 multiplication: 100 After: x = 10, y = 10