Go from Beginner to Expert: A Complete Guide to Learn Golang PART-2
Step-by-Step Guide to build your First Application in Golang
Hello and welcome to this tutorial on the Go programming language!
In this tutorial, we will be discussing the classic “Hello, World!” program, which is a simple program that outputs the message “Hello, World!” to the console.
If you haven’t setup up the development environment for Go on your Linux machine, you may check this out.
To create a simple program in go, we will create a file and name it `main.go which contains the following code:
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
Let’s break down this code to understand what each part does.
The first line, package main, indicates that this is the main package for the program. In Go, a package is a collection of related Go source files that are compiled together.
The next line, import “fmt”
, is an import statement, which tells the Go compiler to include the code from the fmt
package in our program. The fmt
package contains functions for formatting and printing output, such as Println, which we will see later.
Next, we have the func main()
block, which is the entry point for our program. This is where the program will start executing when it is run.
Inside the main() function
, we have a single line of code: fmt.Println(“Hello, World!”)
. This line calls the Println function from the fmt package, which stands for “print line”, and prints the string “Hello, World!” to the console.
And that’s it! When you run this program using this command:
$ go run main.go
The above command will give output “Hello, World!” to the console.
To transform the source file into an executable (a binary), we will use the Go toolchain. Open a terminal and type:
$ go build main.go
The above command will compile the program into an executable. The executable is named main (the same name as the source file, without the .go
extension)
WARNING! be sure that you only use packages that you actually import. Otherwise your program will not compile. When you use a package not imported, your Go program will not compile
I hope this will help you to create your first application in Golang. Let me know if you have any questions.
That’s all for this part.
Let’s check out the next part where we will discuss on Variables, constant and types in Golang.
Kindly explore the complete series on Golang, which presents a step-by-step guide, available here.