Get Going with GoLang

An Introduction

Get Going with GoLang

Introduction

GoLang is a fairly new language that first appeared back in 2009 created by Google developers. It is a statically typed and compiled programming language. It is similar to C in syntax but with added features like an advanced garbage collector, memory safety, structural typing, concurrency, and parallelism. Its built-in package system is spectacular and has a variety of packages which makes it internet-ready out of the box.

Advantages of using Go

  • It is FASSTTT as it is compiled language
  • It is EASY to LEARN as it was created with similar syntax to C but with ease of understanding as in Python or JavaScript. It has the same procedural programming approach as for C++ or JAVA.
  • It is highly SCALABLE. Go was built by Google keeping scalability as the first priority. It is the most efficient language for creating backend servers. Thanks to the features like Goroutines(multiple functions running simultaneously and independently), it has a very low memory signature and it is very fast.
  • It has a very ROBUST in-built package system. For example, it is bundled with an inbuilt net/http library which is capable of creating production-level servers instantly.

Usage of Go

Due to its highly scalable, storage efficiency, and fast nature, it is widely used in creating server-side applications. Google created this language and uses it for their internal projects. Google Earth, Google Chrome, and Youtube all use Go. Uber is another tech giant using Go for their geofencing services and implementing dynamic price models in their system, owing to its speed and high reliability. Companies like Dropbox, Soundcloud, and Twitch use Go for their servers. Check Out


Installing Go Compiler

Let's start with installing the go-compiler on our machines. Just visit this link and follow the required steps to install the compiler in your systems.

Then type the following command in your terminals after installing to check the compiler version and whether it's properly installed or not.

go version

As of now, I am working on version 1.18.

All on board?


Writing the Hello World program

Open a new file with the name "main.go" in your favorite code editor, I am using GoLand by JetBrains, and as the tradition goes, let's create a simple hello world program.

package main

import "fmt"

func main(){
      fmt.Println("Hello, World !!")
}

Now save the file, and open your terminal in your present directory. To execute this program, enter the following command in your terminal.

go run main.go

Note: If you get an error regarding your .exe file, try turning off the antivirus in your system.

This program should output "Hello, World !!" in your terminal.

Here is an explanation of what we just did !! The first line package main defines this program as the main go file in the directory. The func main() is where the program starts executing, every main package should have a main function to start the execution of the program. Then we utilize the standard fmt library to print hello world in the terminal. This library is part of the standard libraries that come bundled with the compiler, out of the box.


Variables in Go

If you are coming from a pure javascript or python background, you might not be aware of the statically typed syntax of Go, where you should define the data type and return type of variables and functions beforehand.

Declaring Variables in Go

Syntax - var <variable name> <datatype>

var myInt int    //Integer Variable
var myString string    //String Variable
var myFloat float32    //Float Variable
var myBool bool    //Boolean Variable

Shorthand :=

Another Syntax or Short-hand := for initializing variables when we don't know what would be the type (in case of a function returning some data):

myVar := someFunctionWithSomeReturnValue()

Assigning Values to Variables

var a int = 10
//or
var b int
b = 20
//Multivariable initialization
c,d := 100,3.14
// string
s := "Welcome to Golang"

Constant Variables

const a int = 5
const (
    b = 10
    s = "I am constant"
)
  • const keyword is used to make a variable constant and immutable in a program.

Functions in Go

Function Prototype - func <function name>(<parameters type>) <return type> {}

func addNumbers(x,y int) int {
      sum := x+y
      return sum
      //or
      return x+y
}

This is the syntax in which we declare functions in Go. The input parameters should be defined with their data types.

  • func => It is the keyword to declare a function in Go
  • parameters => It is optional, it contains the list of input and its datatype that the function accepts.
  • return type => It is optional and specifies what will the function return.

Let's make a program to check if a number is a palindrome or not

main.go

package main

import "fmt"

func main(){

    ans := checkPalindrome(121)
    fmt.Println(ans)

}

func checkPalindrome(x int) bool {

    var temp int = x //to store value of x
    var rev int = 0  //to store the reversed number

    for temp != 0 {
        rev = (rev * 10) + (temp % 10)
        temp /= 10
    }

    if rev == x {
        return true
    } else {
        return false
    }
}

Run this program by going to the terminal in your project directory and executing this command

go run main.go

This program uses everything which we learned in the above sections, apart from the for temp !=0 part, the while loop in Go is substituted by the for keyword which works as a while loop.

More Programs to try

  • Fibonacci Series Generator
  • Getting input from the command line
  • Create and work with arrays (or slices as they are called in Go)

You can also check out this repository for more programming examples and topics in Go that will be covered further.

In the next article, I will talk about Pointers, Interfaces, Structs, Slices, and Maps which are the more advanced and commonly used features in GoLang. Stay tuned !!


Thank You :) Keep Learning !! and do follow me on Github

Buy Me A Coffee