You already wrote your first Go program:
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}Let's analyze the each line of code.
The first statement is package main.
A package is a collection of Go files. It is like a folder in a file system.
Some rules for packages:
- each go file must start with a
packagedeclaration - each go file can have only one
package - each
packagename should be:- lowercase
- a single word, no underscores or mixedCaps
Lastly, package named main is special.
Will tell you at the end why it is special.
For now, let's move on to the next statement.
Next is the import statement.
import is used to import packages into your program.
Think of it as a way to use someone else's code in your program.
We imported the fmt (short for "format") package.
fmt is a built-in package, used to format text, print messages to the terminal, and read user input.
In our example, we used fmt.Println to print "Hello, World!" to the terminal.
Next is the func main() statement.
func is a keyword used to define a function.
We will talk a lot about functions in Chapter 6.
For now, just know that func main() is special function.
Together, package main and func main() are the entry point of the Go program.
Everything between the curly braces in func main() {...} will be executed when the program is run.
Now you know the basic structure of a Go program.
Continue to the next topic 👇
