Go Language Tutorials: Structure of a program

Go Language Tutorials: Structure of a program

Go Language Tutorials
Go Language Tutorials


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 -

Declare a package

Import Packages

Declare variables

Write functions

Comments

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 -

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.

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.

Now the next line is func main() which is the main function where the program begins to execute.

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.

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.

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 -

First, open up a text editor and write the above code.

Then, save the file as helloWorld.go

Open up the terminal or command prompt

Go to the path where you saved your Go file.

Then type go run helloWorld.go and press enter to execute the code.

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.

Post a Comment

0 Comments