Introduction to Go Functions
Start with Introduction to Go Functions
A function is a named block of code that performs a task. Functions let you reuse an operation instead of copying the same statements throughout a program.
What you’ll learn
- Explain the main purpose of introduction to go functions.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
Declare a function with func, followed by its name, parentheses and a body in braces. In func greet() { ... }, the empty parentheses mean the function accepts no arguments. Declaring a function does not run it: execution reaches the body only when the function is called.
main() is a special function: it is the entry point of an executable program. You can declare other functions in the same package and call them from main. Functions improve clarity when each name describes a meaningful responsibility.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import "fmt"
func greet() {
fmt.Println("Welcome to Go")
}
func main() {
fmt.Println("Before greeting")
greet()
fmt.Println("After greeting")
}
Output
Before greeting
Welcome to Go
After greetingTrace what the program does
Execution begins in main. The first line is printed, then the call to greet() transfers control to the function body. When it finishes, execution resumes at the statement after the call. The function definition itself did not print anything.
Avoid common mistakes
- A declaration such as
func greet()does not execute until it is called. - A function must have a unique name within its package scope; Go does not support overloading functions by parameter types.
Try it yourself
Add a farewell() function that prints Goodbye, and call it after the greeting.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Introduction to Go Functions in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.