Package Declaration
The program begins with the package declaration: package main This line defines the package name. In Go, every program starts with a package declaration. Packages help organize and reuse code. When building standalone executable programs, the special package “main” is used to indicate the entry point.Import Statement
Next is the import statement: Theimport keyword brings code from external packages into your program. Here, the "fmt" package is imported, which provides input and output formatting functions. Note that the package name is enclosed in double quotes, which is the correct syntax in Go.
Comments
Comments are essential for documenting your code. They are ignored during compilation. In Go, comments can be written in two ways:Single-Line Comments
// This is a single line comment. Single-line comments start with two forward slashes (//). They are ideal for brief explanations.
Multi-Line Comments
/* This is a multi-line comment. */ Multi-line comments are enclosed within/* and */ and are useful for longer explanations.
Function Declaration
The next part of the program is the function declaration: func main() Here’s what happens:- Entry Point: The
mainfunction is the entry point of a Go program. When the program runs, themainfunction is executed automatically. - Function Body: The statements within the curly braces
{ }define what happens when the program starts.
Inside the Main Function
Within themain function, we have:
fmt.Println(“Hello, World”)
This statement has three main elements:
- Package Name:
fmtis the package that provides the necessary functionalities for formatted I/O. - Function Name:
Printlnis a function within thefmtpackage. It prints its argument to the console and adds a newline at the end. - Argument:
"Hello, World"is the string that is passed to thePrintlnfunction for output.
Complete Code Example
Below is the complete code snippet with proper syntax highlighting:Understanding the structure of a basic Go program is crucial before diving into more complex topics like functions, variables, and data types.
main function that serves as the starting point of the program.
Let’s proceed to get some hands-on practice and explore more advanced features of Go!