Thursday, February 2, 2017

Go - Program Structure

Before we study basic building blocks of the Go programming language, let us look a bare minimum Go program structure so that we can take it as a reference in upcoming chapters.

Go Hello World Example

A Go program basically consists of the following parts:
  • Package Declaration
  • Import Packages
  • Functions
  • Variables
  • Statements & Expressions
  • Comments
Let us look at a simple code that would print the words "Hello World":
package main

import "fmt"

func main() {
   /* This is my first sample program. */
   fmt.Println("Hello, World!")
}
Let us look various parts of the above program:
  1. The first line of the program package main defines the package name in which this program should lie. It is a must statement as Go programs runs in packages. main package is the starting point to run the program. Each package has a path and name associated with it.
  2. The next lineimport "fmt" is a preprocessor command which tell the Go compiler to include files lying in package fmt.
  3. The next line func main() is the main function where program execution begins.
  4. The next line /*...*/ will be ignored by the compiler and it has been put to add additional comments in the program. So such lines are called comments in the program. Comments are also represented using // similar to Java or C++ comments.
  5. The next line fmt.Println(...) is another function available in Go which causes the message "Hello, World!" to be displayed on the screen. Here fmt package has exported Println method which is used to display message on the screen.
  6. Notice the capital P of Println method. In Go language, a name is exported if it starts with capital letter. Exported means that a function or variable/constant is accessible to importer of the respective package.

Execute Go Program:

Lets look at how to save the source code in a file, and how to compile and run it. Following are the simple steps:
  1. Open a text editor and add the above-mentioned code.
  2. Save the file as hello.go
  3. Open a command prompt and go to the directory where you saved the file.
  4. Type go run hello.go and press enter to run your code.
  5. If there are no errors in your code then you will be able to see "Hello World" printed on the screen.
$ go run hello.go
Hello, World!
Make sure that go compiler is in your path and that you are running it in the directory containing source file hello.go.

No comments:

Post a Comment