bugl
bugl
HomeLearnPatternsPathsSearchPremium
HomeLearnPatternsPaths
Learn/Go/Go Tutorial
Go•Go Tutorial

Go Functions

A function is a block of statements that can be used repeatedly in a program.

A function will not execute automatically when a page loads.

A function will be executed by a call to the function.

Create a Function

To create (often referred to as declare) a function, do the following:

  • Use the func keyword.
  • Specify a name for the function, followed by parentheses ().
  • Finally, add code that defines what the function should do, inside curly braces {}.

Syntax

func
FunctionName
() {
 // code to be executed
}

Call a Function

Functions are not executed immediately. They are "saved for later use", and will be executed when they are called.

In the example below, we create a function named "myMessage()". The opening curly brace ( { ) indicates the beginning of the function code, and the closing curly brace ( } ) indicates the end of the function. The function outputs "I just got executed!". To call the function, just write its name followed by two parentheses ():

Example

package main
import ("fmt")
func myMessage() {
  fmt.Println("I just got executed!")
}
func main() {
  myMessage() // call the function
}

A function can be called multiple times.

Example

package main
import ("fmt")
func myMessage() {
  fmt.Println("I just got executed!")
}
func main() {
  myMessage()
  myMessage()
  myMessage()
}

Naming Rules for Go Functions

  • A function name must start with a letter
  • A function name can only contain alpha-numeric characters and underscores ( A-z , 0-9 , and _ )
  • Function names are case-sensitive
  • A function name cannot contain spaces
  • If the function name consists of multiple words, techniques introduced for multi-word variable naming can be used

Tip

Give the function a name that reflects what the function does!

Previous

Go For Loops

Next

Go Function Parameters and Arguments

This chapter

Overview
39

Lessons

95m

Read time

1. Go Tutorial2. Go Introduction3. Go Getting Started4. Go Syntax5. Go Comments6. Go Variables7. Go Multiple Variable Declaration8. Go Variable Naming Rules9. Go Constants10. Go Output Functions11. Go Formatting Verbs12. Go Data Types13. Go Boolean Data Type14. Go Integer Data Types15. Go Float Data Types16. Go String Data Type17. Go Arrays18. Go Slices19. Go Access, Change, Append and Copy Slices20. Go Operators21. Go Arithmetic Operators22. Go Assignment Operators23. Go Comparison Operators24. Go Logical Operators25. Go Bitwise Operators26. Go Conditions27. Go if statement28. Go if else Statement29. Go else if Statement30. Go Nested if Statement31. Go switch Statement32. Go Multi-case switch Statement33. Go For Loops34. Go Functions35. Go Function Parameters and Arguments36. Go Function Returns37. Go Recursion Functions38. Go Struct39. Go Maps

On this page

Create a FunctionCall a FunctionNaming Rules for Go Functions