Simple Golang Program
A volunteer has recorded a new club member’s age as 6. The program starts, reads that stored value and prints it once so the volunteer can check the entry.
Save the following example as SampleProgram.go and run it with go run SampleProgram.go.
package main
import "fmt"
func main() {
// Declare and Initialize an integer variable 'age' with value 6
var age int = 6
// Print the local variable 'age' in the console window
fmt.Println(age)
}
6
A Go source file ends in .go and begins with a package clause.
Identifiers name program elements such as packages, functions, variables, and types. Their declarations determine where they are in scope.
- main - Name of the package
- main names the entry function.
- age names the local variable.
Go reserves certain words for the language. The example uses the following keywords. The name int is a predeclared identifier.
- package declares the package.
- import introduces an imported package.
- func introduces a function declaration.
- var introduces a variable declaration.
Execution of a Go command starts in func main() after package initialization.
A project can contain several commands. Each executable is built from its own main package.
The main function contains a declaration and a call to fmt.Println.
- var age int = 6 declares an integer and assigns the value 6.
- fmt.Println(age) prints the value of age.
Go inserts semicolons automatically at certain line endings. Idiomatic Go omits explicit semicolons in these statements.
Braces group statements into a block, introducing a scope for local declarations.
- The braces delimit the function body.
Put the opening brace on the same line as the function signature so automatic semicolon insertion does not end the declaration early.