1
Write a post

My Journey with Golang: Hello world in Golang

Published May 30, 2017
My Journey with Golang: Hello world in Golang

Yeah, I have been learning Golang for some time now, and it's been awesome. In the next few weeks, I'll be posting several articles about issues I encountered during my learning process.

Why Go

GO is a statically typed language used for building systems applications. Go is fun, intuitive, and easy to learn since you only have like 24 keywords to cover. Go has concurrency built into it, great support (since it’s built by Google), growing developers base, support for popular text editors, IDE with awesome debugging tools, IntelliSense, and code formatting. Not to mention, it is extremely fast to compile. One of the beauties of Go is that it forces you to adhere to good programming principles.

Folder Structure

Who doesn't like a Hello World program? This might sound simple, but we are going to build this Hello World program and compile it down to machine code. During this process, I'll tell you about Go’s folder structure and how to get started with writing GO.

The most challenging part I came across when learning Golang is the difference between $GOROOT and GOPATH.GOPATH. **GOROOT** points to your current Go installation folder
$GOPATH points to your working directory.
Writing Go, you can have multiple working directories for different projects, but this means you'll have to specify a new GOPATH whenever you're about to start working from a different workspace.

I'm on a Mac, so that's the environment I'll be walking you through.
Go to Getting Started and walk through the installation process for your machine. By default, Go installs to /usr/local/go, which would be your default GOROOT. For custom installation, you can set the GOROOT by:

 export GOROOT=$HOME/go1.X = go1.X been the path to your installation
 export PATH=$PATH:$GOROOT/bin - adds the bin folder to your PATH for running go across you system

The default GOPATH for Mac is /Users/{username}/go, you can change that by doing this from your workspace:
For me my workspace is /Users/{username}/documents/golang

 export GOPATH=$HOME/Documents/golang
 export PATH=$PATH:$GOPATH/bin

The second export sets the bin directory where your Go builds would be installed.
You can run Go env to check out your Go environments variable, this also contains the absolute path to your GOROOT and GOPATH.

Your Go workspace will most likely contain three main folders
Screen Shot 2017-05-22 at 7.22.01 AM.png
src: contains Go source files,
pkg: contains package objects, and
bin: contains executable commands.
NB: if you do specify your GOPATH, the default GOPATH in your Go env will be used.

All your code and installed external library go into your src folder. Returns more on Golang folder structure try exploring
golang official documentation
thenewstack

The Hello World

Now let's write some Hello World. In the src folder create a main folder. In that folder create main.go file. This would be your app’s entry point. The main.go file contains the keyword function, this will get executed during runtime.

package main
import (
    "fmt"
)
func main() {
    fmt.Println("hello world")
}

Run go run main.go from your terminal, what you get is
// hello world

The above code sets the main folder as the main package, this tells Go to treat this file as an entry point.
NB: When using the main package the main function is required.
Packages: Go does not care where your files are placed, the package name is the main source of truth, this name must match the folder.
If you have a folder in your src called utils the files in that folder will use package utils.
ASIDE: Methods written with their first letter in caps are automatically exported by Go.

Import: Go imports internal and external libraries using the import keyword. One beauty of Go, though you might find it annoying at first, is if you import a library without using it, Go throws an error. Awesome right? And this goes for declared variables as well.

fmt: The fmt library just contains methods for writing to your terminal, the Println is just one of many methods in the fmt library.
Running the above program will print out Hello World to your terminal.

Awesome, you have just written your very first Go program! Let's go over a final example and make our Hello World program more interactive. By allowing the user to input their name from the terminal, Go will dynamically print their names with a greeting.

    package main

    import (
        "fmt"
        "os"
    )
    
    func main() {
        // cannot be reassigned
        const hello = "Hello"

        // declare a variable in golan
        var world string
        //others
        // int
        // int32
        // int64 this three integers also have a float counterpart

        // assigning a variable
        world = "guest"

        // go offers dynamic assignment
        geetings := " have a wonder full weekend"
        if len(os.Args) > 1 {
            fmt.Println(hello + " " + os.Args[1] + geetings)
        } else {
            fmt.Println(hello + " " + world + geetings)
        }
    }

I wrote this example so I could point out some more keywords in Go.
CONST: if you have been programming for a while now, you must have come across this. Const in Go cannot be reassigned.

  const (
      Name = "Murphy"
      Age = 40
      Nationality = "Nigeria"
  )
  name = "Enaho" // throws an error: cannot assign to name

That is how multiline const is declared trying to reassign name throws an error during compile time.

VAR: This is used for creating variables. If you have written JavaScript before then you must have used this keyword. Because Go is statically typed, you need to declare the variable type. Variables declared with var can be reassigned.

  var Name string = "Enaho"
  var Age int64 = 40
  var Nationality string = "Nigeria"


  Name = "Murphy"
  Age = "40" // throws an error: cannot use "40" (type string) as type int64 in assignment
  fmt.Println(Name) // Murphy

Dynamic Assignment: Go also gives you the ability to dynamically assign values to variables. Based on the value on the right-hand side of your expression, Go will automatically cast the variable on the left-hand side to the proper data type.
From our second example above you can see greetings were declared and assigned without specifying the type, Go knows to make greetings a type string when you use
:= to assign the value.

The above code uses a method in the os library to get all values you type after running your go program.

    go run main.go murphy // Hello murphy have a wonderful weekend

The args returns an array of values based on the number of words you typed after the main.go, the first being the absolute path to the file. Try logging out of os.Args on your workspace and see what you get.
Screen Shot 2017-05-22 at 7.57.34 AM.png

Creating a Golang Executable

This is simple, just run go build main.go
This creates an executable called main, by running ./main creates the same output as go run main.go

Another command you might want to know about is the ** go install ** This command installs your app to the bin directory in your GOPATH making it accessible anywhere across your system.

You need to add two more env for this to work.

    export GOBIN=$GOPATH/bin
     export PATH=$PATH:$GOPATH/bin

Gobin sets the Go bin directory where you installed the executable.
The PATH just tells your system where to find your executables.

Summary

This is one long Hello World program and a lot has been written. But there is more to learn. This article just introduces you to the beauty of Go to get you started.
It will do you a lot of good to explore the official golang documentation.
You can also follow the try Go interactive tutorial .

Finally, Golang offers a playground here.

Kindly drop your comment if you have any issues with the suggestions I have made in the article. Feedback is greatly appreciated as it improves my learning and also helps Golang beginners.

This will be the first of its series as we explore the language Go together.

Discover and read more posts from Murphy Enaho
get started
Enjoy this post?

Leave a like and comment for Murphy

1
Be the first to share your opinion

Subscribe to our weekly newsletter