Hello World Example GoLang

As a programmer, it is a commonly followed practice to print hello world in the language which you are starting to learn. In this article we will see how to write a hello world program in Go Lang.

Before we start it is assumed, that you have a go development environment up and running.

Hello World in Go

  • Create a directory where you want to save the code for your hello-world application. For this article, I'm naming it as hello
  • Create a file with .go extension , and it is preferred to name it as main.go if the code is the starting point of a program.
    • The file name should be lowercase with no spaces

Below code snippet shows the hello world program,

[root@LDH hello]# pwd
/root/hello
[root@LDH hello]# cat main.go
package main
// Comments need to be added after'//'
import {
"fmt"
}

func main() { // this curly braces need to be in the same line as the function
    fmt.Println("Hello, world.")
}
  • In the above snippet, it can be seen that
    • Comments need to be put after "//"
    • Since this is a startup code for our application which print "Hello world" , this file need to be  a member of a package called main
    • Import is used to import the packages required for our application, in our case im using a package called "fmt"
    • fmt is a formating package, which is used for printing values
    • Since this is a startup file, a function named main need to be present.
    • Println which is part of fmt package will print the String
  • For running the go code, we can use go run
[root@LDH hello]# go run main.go
Hello, world.
  • For building the go binary, we can use go build
  • A binary named hello will be generated. ( binary will take the name of the directory, if our code name is main.go ifnot it will take the codename)
  • We can execute the binary directly.
  • Below snippet shows all execution
[root@LDH hello]# go build main.go
[root@LDH hello]# ll
total 1724
-rwxr-xr-x. 1 root root 1758428 Jul 24 01:51 hello
-rw-r--r--. 1 root root 77 Jul 24 00:26 main.go
[root@LDH hello]# ./hello
Hello, world.

Search on LinuxDataHub

Leave a Comment