Go Functions
Think of a function as a named block of statements that you can reuse as often as your program needs it.
Declaring a function does not run it, so nothing happens automatically. Its code runs only when the function is called.
Create a Function
Declaring a function (another word for creating one) takes three steps:
- Begin with the
funckeyword. - Give the function a name and put parentheses () after it.
- Inside curly braces {}, write the code the function should run.
Function Syntax
main.go
func FunctionName() {
// code to be executed
}
Call a Function
Go does not run a function at the moment you declare it. The code is kept ready and only runs once the function is called.
A call is simply the function's name with two parentheses () after it.
Example
Prompt
Create a function called myMessage that prints "I just got executed!" and call it from main.
Output: Go program and captured output
main.go
package main
import ("fmt")
func myMessage() {
fmt.Println("I just got executed!")
}
func main() {
myMessage()
}
Example
You are free to call the same function as many times as you like. Here it runs three times.
Prompt
Create a function called myMessage that prints "I just got executed!" and call it three times from main.
Output: Go program and captured output
main.go
package main
import ("fmt")
func myMessage() {
fmt.Println("I just got executed!")
}
func main() {
myMessage()
myMessage()
myMessage()
}
Naming Rules for Go Functions
- The first character has to be a letter.
- Only alpha-numeric characters and underscores are allowed (
A-z,0-9, and_). - Case matters: names that differ only in upper and lower case are different functions.
- Spaces are not allowed.
- For a name made of several words, use the same multi-word techniques you learned for variable names.
Tip: Choose a name that tells the reader what the function does.