Create and Call Functions in Go #
Functions in Go allow you to organize code into reusable blocks. You can create a function and call it whenever needed.
Creating a Function #
To create (or declare) a function in Go:
- Use the
func
keyword. - Specify a name for the function, followed by parentheses
()
. - Add code inside curly braces
{}
that defines what the function should do.
Syntax:
func FunctionName() {
// code to be executed
}
Calling a Function #
Functions are not executed immediately. They are executed only when called.
Example:
package main
import "fmt"
func myMessage() {
fmt.Println("I just got executed!")
}
func main() {
myMessage() // call the function
}
Result:
I just got executed!
A function can also be called multiple times:
package main
import "fmt"
func myMessage() {
fmt.Println("I just got executed!")
}
func main() {
myMessage()
myMessage()
myMessage()
}
Result:
I just got executed!
I just got executed!
I just got executed!
Naming Rules for Go Functions #
- Must start with a letter
- Can contain letters, numbers, and underscores (
A-z
,0-9
,_
) - Case-sensitive
- Cannot contain spaces
- For multi-word names, use camelCase or PascalCase for readability
Tip: Give functions descriptive names that indicate what they do.
Functions are fundamental to structuring Go programs, allowing you to write clean, reusable, and modular code.