In Go, functions are reusable blocks of code designed to perform specific tasks. These code blocks allow developers to organize their programs into smaller, manageable sections. A function does not run automatically; it must be explicitly called in the program.
Declaring Functions
To declare (or create) a function, follow these steps:
- Use the
func
keyword. - Provide a name for the function, followed by parentheses
()
. - Write the desired code for the function inside curly braces
{}
.
Syntax:
func FunctionName() {
// code to execute
}
Calling a Function
Functions are dormant until called. To execute a function, simply write its name followed by parentheses ()
.
Example: Here, we define a function named motorcycleBrands()
. It prints a message when executed:
package main
import ("fmt")
func motorcycleBrands() {
fmt.Println("Function was executed!")
}
func main() {
motorcycleBrands() // Call the function
}
Output:
Function was executed!
Reusing Functions
Functions can be reused by calling them multiple times within the same program.
Example: In this case, the function motorcycleBrands()
is called three times:
package main
import ("fmt")
func motorcycleBrands() {
fmt.Println("Function was executed!")
}
func main() {
motorcycleBrands()
motorcycleBrands()
motorcycleBrands()
}
Output:
Function was executed!
Function was executed!
Function was executed!
Function Naming Rules
When naming functions, ensure the following:
- Names must begin with a letter.
- Use only alphanumeric characters and underscores (_); no special characters or spaces.
- Names are case-sensitive, meaning
MyFunction
andmyfunction
are considered distinct. - Multi-word names should follow accepted naming conventions, such as camelCase or snake_case.
- Names should describe the function’s purpose for readability.
Tip for Naming
Always give your functions meaningful names that explain what they do. For example, a function that lists motorcycle brands might be named listMotorcycles()
or showBrands()
.