0
0
Goprogramming~5 mins

main package and main function in Go

Choose your learning style9 modes available
Introduction

The main package and main function are the starting point of a Go program. They tell the computer where to begin running your code.

When you want to create a program that runs by itself.
When you want to build a command-line tool or application.
When you want to test how your code works by running it directly.
When you want to organize your code so it can be executed as a program.
Syntax
Go
package main

import "fmt"

func main() {
    // code to run
}

The package must be named main for the program to be executable.

The main function is where the program starts running. It has no parameters and no return value.

Examples
This example prints a greeting message when the program runs.
Go
package main

import "fmt"

func main() {
    fmt.Println("Hello, world!")
}
A minimal program with an empty main function that runs but produces no output.
Go
package main

func main() {
    // This program does nothing
}
Sample Program

This program prints a welcome message to the screen when you run it.

Go
package main

import "fmt"

func main() {
    fmt.Println("Welcome to Go programming!")
}
OutputSuccess
Important Notes

Only one main package and main function can exist in a single executable program.

The main function cannot take arguments or return values.

Summary

The main package is the entry point for Go programs.

The main function is where the program starts running.

Use them to create runnable Go applications.