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
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:
- 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.
- The next lineimport "fmt" is a preprocessor command which tell the Go compiler to include files lying in package fmt.
- The next line func main() is the main function where program execution begins.
- 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.
- 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.
- 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:- Open a text editor and add the above-mentioned code.
- Save the file as hello.go
- Open a command prompt and go to the directory where you saved the file.
- Type go run hello.go and press enter to run your code.
- 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