Go Basics
Go Language Basics
GETTING STARTED WITH GO PROGRAMMING BASICS
Program Structure:
Let us first discuss the basicstructure of Go programs so that we can take it as a reference in subsequent chapters.
Basic parts of a Go program:
- Statements and Expressions
Now let’slook at a simplecode that would print“Hello world”
Package declaration
The first line of the program defines the main package which is the mandatory statementas Go programs run in packages.
Import Packages
The very next line of the program is import “fmt” which is a preprocessor command that orders the Go compiler to add the files within the package fmt.
The func main() in the next line is the main function where the program execution starts.The fmt.Println(...) in the next line is the print function available in Go to display the contents on the screen. The Println function is exported by the fmt package. The capital P in Println shows this is exported. In Go, thename is exported if it begins with the capital letter. Exported means the variable/constant/function is accessible to the importer of the corresponding package.
The /*...*/ in the next line is the comment statement which is used toadd comments to the program. This comment line will be ignored by the compiler. The comment statement can also be represented using // like in Java or C++.
Go Program Execution:
- Open a text editor and add the above given example program code.
- Save that file as “helloworld.go”
- Now open the commandprompt and go to the directory where the go program file resides.
- Enter the command go run helloworld.goto run the program.
- If your code doesn’t contain any errors,you cansee the “Hello World!” displayed on the screen.
Syntax
Output : $ go run helloworld.go //This is the execution comment used for go program Hello, World!