Program Structure and Syntax
In Go, a package is the basic unit of code management. Every Go program begins with a package
declaration. In this case, package main
tells Go that the code is part of the main program that will be executed.
The import "fmt"
statement imports the Go fmt
package, which is used for input and output. Go has a rich standard library, which allows us to perform many tasks with ease. The fmt
package is used to format text output, as we saw in the previous step.
Next, we define the main
function:
func main() {
}
In Go, all functions must begin with func
. Notice that the opening brace {
is placed at the end of the line. This is a Go convention, and it’s different from other programming languages that might place the opening brace on a new line.
If you mistakenly place the opening brace on a new line like this:
func main()
{
}
You will get a compilation error:
$ go run helloWorld.go
### command-line-arguments
./helloWorld.go:7:1: syntax error: unexpected semicolon or newline before {
This is because Go expects the opening brace to be directly on the same line.
The key statement in the program is fmt.Println("hello, world")
, which calls the fmt
package's Println
function to print the string "hello, world"
to the console. This function automatically adds a newline character at the end of the string.