Go Functions

Gayathri. B

 Defining a Function in Go

To declare a function in Go, follow these steps:
     1.Begin with the func keyword.
     2.Write the function’s name right before a set of parentheses ().
     3.Enclose the instructions the function should run within curly braces { }.
Syntax:
func FunctionName() {
    // code to be executed
}

Calling a Function in Go

  • In Go, functions are not executed as soon as they are defined. Instead, they are stored and run only when explicitly called.
  • In the following example, we define a function named myMessage(). The function body is enclosed between { and } and contains a statement that prints a message. To execute the function, we simply call it by writing its name followed by parentheses ().

Example 2:

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

Output:

I just got executed!

Example 2:

package main
import "fmt"
// Define a function named displayMessage
func displayMessage() {
  fmt.Println("I just got executed!")
}
func main() {
  // Call the function three times
  displayMessage()
  displayMessage()
  displayMessage()
}

Output:

I just got executed!
I just got executed!
I just got executed!

Rules for Naming Functions in Go:

  • A function name must begin with a letter.
  • It can include only letters, digits, and underscores (A–Z, a–z, 0–9, and _).
  • Function names are case-sensitive (MyFunc and myFunc are different).
  • Spaces are not allowed in function names.
  • For function names with multiple words, use naming styles like camelCase or PascalCase, similar to variable naming.
✅ Tip: Choose a name that clearly describes what the function does to make your code more readable and maintainable.



Tags
Our website uses cookies to enhance your experience. Learn More
Accept !

GocourseAI

close
send