Go Language Tutorials: Structure of a program
Before proceeding further to the basics of Go language, let me show you the bare minimum structure of Go programs so that it can help us as a reference in upcoming chapters.
Basic Example
A program is written in Go basically consists of the following parts -
u Declare a package
u Import Packages
u Declare variables
u Write functions
u Comments
u Expressions and Statements
Let me show you a simple program that prints “Hello-World!” -
package main
import “fmt”
func main(){
// This is a simple code
fmt.Println(“Hello-World!”)
}
So now let's take a look at various parts of the above program -
u The first line defines the package name and it is mandatory because programs written in Go run in packages. The main package runs as a starting point to run the program. Each package in the Go environment has a path and name associated with it.
u The next line is an import statement, it is a preprocessor command which directs the compiler to include all the files which lie in package fmt.
u Now the next line is func main() which is the main function where the program begins to execute.
u The next is a comment line that is ignored by the Go compiler and it is used to add comments in the source program. Comments are also declared using /**/ similar to C or Kotlin.
u fmt.Println() is a function that is available Go library which writes the message “Hello-World!” so it will get printed on the console. The fmt package has the Println method so that it can be used to show the message on the console.
u The P is capital in Println() method. So In the Go programming language, a name is said to be exported if it starts with a Capital letter.
Let us execute a Go program
Let me show you how to save the source code and then compile it, and then execute the program.
Follow the below steps -
u First, open up a text editor and write the above code.
u Then, save the file as helloWorld.go
u Open up the terminal or command prompt
u Go to the path where you saved your Go file.
u Then type go run helloWorld.go and press enter to execute the code.
u If your code compiled successfully, then you will see “Hello-World!” displayed to you.
C:/>go run helloWorld.go
Hello-World!
Please make sure that you have added the Go compiler in your system path and also ensure that you are running this command inside the path where helloWorld.go is located.
0 Comments