Golang: for beginners - Part 1: Getting started and variables

Golang: for beginners - Part 1: Getting started and variables

Golang is a statically typed, compiled programming language from Google developed by industry veterans like Robert Griesemer, Rob Pike and Ken Thomson. Golang is inspired from C language but with additional features like memory safety, garbage collection, structural typing and concurrency. It most used language in cloud native projects like Kubernetes, buidling web apis, CLI tools etc. It also has a self hosting compiler that can compile to multiple operating systems and web-assembly.

So, how to get started with Go?

Installing

Go binaries are available from golang.org or if you are using Homebrew on macOS or linux you can use

brew install go

Hello World

Following the ritual of writing hello world program when ever you learn a new programming language. Previously, you needed to create project directory inside GOPATH but after release of go mods it is not necessary. Create a folder with name of your choice, I will use tutorial and run

go mod init tutorial

You don't to name your module same as folder name but people prefer to do so. Also, if its open source project people use there github link like if I have to create for myself, github.com/ratnadeep007/tutorial but for now only tutorial will suffice.

After running previous command you will find it create a file called go.mod, if is used to manage all dependencies for you go project and also it has your go version. We will not use this file in this tutorial as we will not use any third party package. Following is my go.mod file.

module tutorial

go 1.16

Create a file main.go which will be used as entry point for our program. You can name is anything you like server.go or entry.go that doesn't matter. By convention I am using main.go. I am assuming you entry point to be main.go.

Write following code in main.go

package main

import "fmt"

func main() {
    fmt.Println("Hello")
}
  1. package main defines entry point for your program, if you don't have package main in your program go compile will complain it couldn't find main package.
  2. import "fmt" imports "fmt" package in your project which has formatted I/O functions, its a inbuilt package in golang.
  3. func keyword is used to declare a function.
  4. func main() is entry point function for any golang program just like C. First function called by golang is main.
  5. fmt.Println("Hello World") using Println function from fmt package to print a line in stdout or your terminal.

How to run it?

Even being a compiled language you don't need to compile golang to run it, you can use following to run it.

$ go run main.go
Hello World

How to build executable

While developing go run main.go is good but how you distribute your program as executable. Following command compile your code and create executable named tutorial.

$ go build -o tutorial
$ ./tutorial
Hello World

How to store value?

Golang or most of the modern languages even being statically typed has feature called inference by which can decide type of variable without explicitly defining type.

package main

import "fmt"

func main() {
    num := 1
    fmt.Println(num)

    var num1 int
    fmt.Println(num1)
}
  1. num := 1 here compiler will infer type of variable from initialized value, := operator is used for intference.
  2. var num1 int we are explicitly defining variable num1 as int as we don't want to initialize it now.

What values we can store?

Like other programming languages Golang also supports different variable types. fmt.Printf("%T", num) can be used to check variable type. Yes, golang supports C-style printf as one of the developer is Ken Thomson who developed C.

Following are datatypes that golang supports:

Signed Integers

TypeSizeRange
int88 bits-128 to 127
int1616 bits-215 to 215-1
int3232 bits-231 to 231-1
int6464 bits-263 to 263-1
intPlatform DependentPlatform Dependent

Unsigned Integers

TypeSizeRange
uint88 bits0 to 255
uint1616 bits0 to 216-1
uint3232 bits0 to 232-1
uint6464 bits0 to 264-1
uintPlatform DependentPlatform Dependent\

Platform dependent means if its running on 32-bits system it will 32-bits and if its running on 64-bits system it will be 64-bits.

Golang provides type alias for following:

TypeAlias
byteunit8
runeint32

They are used to distinguish character value from integer values as Golang doesn't character data type. byte is used to represent ASCII character and rune is used for Unicode characters.

package main
import "fmt"

func main() {
    var myByte byte = 'a'
    var myRune rune = '♥'

    fmt.Printf("%c = %d and %c = %U\n", myByte, myByte, myRune, myRune)
}

Floating Types

There are 2 floating types:

  1. float32 uses single precision floating point format and uses 32 bits in memory
  2. float64 uises double precision floating point format and uses 64 bits in memory

Default type for floating point number is float64.

Boolean

Golang has boolean type bool which can be used to store true or false.

package main

import "fmt"

func main() {
    bool1 := true
    fmt.Println(bool1)

    var bool2 bool
    bool2 = false
    fmt.Println(bool2)

    var bool3 = true
    fmt.Println(bool3)
}

Complex Numbers!!!

Golang has in-built support for complex numbers which can be created using complex function. Following are types of complex data:

  1. complex64 - both real and imaginary part are float32 type
  2. complex128 - both real and imaginary part are float64 type

Default is complex128.

package main

import "fmt"

func main() {
    // Using default type
    var complex1 = 1 + 6i
    fmt.Println(complex1)

    // Using complex function
    var1 := 1.2
    var2 := 2.3
    vComplex := complex(var1, var2)
    fmt.Println(vComplex)

    // Operations on complex number
    c1 := 1 + 1i
    c2 := 2 + 2i
    add := c1 + c2
    sub := c1 - c2
    mul := c1 * c2
    div := c1 / c2
    fmt.Printf("%v + %v = %v\n", c1, c2, add)
    fmt.Printf("%v - %v = %v\n", c1, c2, sub)
    fmt.Printf("%v * %v = %v\n", c1, c2, mul)
    fmt.Printf("%v / %v = %v\n", c1, c2, div)
}

Output

$ go run main.go
(1+6i)
(1.2+2.3i)
(1+1i) + (2+2i) = (3+3i)
(1+1i) - (2+2i) = (-1-1i)
(1+1i) * (2+2i) = (0+4i)
(1+1i) / (2+2i) = (0.5+0i)

Strings

In Golang, a string is a sequence of bytes. There are 2 ways of declaring string, using double quotes " and using back ticks . Difference between them is double quotes can't have multi line string but can use escape characters like\nand\t`.

package main

import "fmt"

func main() {
    str1 := "Double quotes string can't be multi line. \nEscape characters can be used to create new line or tabs"
    str2 := `Back Ticks is used if we need multi line support.
It keeps format of string with new line, tabs, whitespaces etc intact.`
    fmt.Println(str1)
    fmt.Printf("\n")
    fmt.Println(str2)
}

Converting Numerical types

Golang provides easy way to covert numerical types, take any data type and make it a function and pass value you want to convert.

package main

import "fmt"

func main() {
    // Converting float to int
    f := 2.1
    i := int(f)
    fmt.Printf("%T\n", i)

    // Converting float32 to float64
    var a float32 = 2.1
    fmt.Printf("%T\n", a)
    b := float64(a)
    fmt.Printf("%T\n", b)

    // Convert int to unit
    j := -1
    fmt.Printf("%T\n", j)
    k := uint(j)
    fmt.Printf("%T\n", k)

    // Convert int32 to int64
    var c int32 = 32
    fmt.Printf("%T\n", c)
    d := int64(c)
    fmt.Printf("%T\n", d)
}

Output

$ go run main.go
int
float32
float64
int
uint
int32
int64

Converting to string to other data type or vice-versa

Golang provides handy package/module for converting string to numbers or numbers to string strconv.

package main

import (
    "fmt"
    "strconv"
)

func main() {
    // Converting string to a int
    a := "12"
    b, _ := strconv.Atoi(a)
    fmt.Printf("%T\n", b)

    // Converting int to string
    c := 1
    d := strconv.Itoa(c)
    fmt.Printf("%T\n", d)

    // Converting string to float32
    x := "1.2"
    y, _ := strconv.ParseFloat(x, 32)
    fmt.Printf("%T\n", y)

    // Convert float to string
    e := 1.2
    f := fmt.Sprintf("%f", e)
    fmt.Printf("%T\n", f)

    // String to boolean
    g := "true"
    h, _ := strconv.ParseBool(g)
    fmt.Printf("%T\n", h)

    // Boolean to string
    i := false
    j := strconv.FormatBool(i)
    fmt.Printf("%T\n", j)

    // String to complex
    k := "3 + 2i"
    l, _ := strconv.ParseComplex(k, 64)
    fmt.Printf("%T\n", l)
}

When converting string to float and string to complex you need to pass bit, but still it will convert to its default type that is float64 and complex128, but these are convertible to float32 and complex64 without changing its value.

For float you can format it in many different ways, following table shows it:

FormattingDescriptionVerb
1.234560+e02Scientific notation%e
123.456000Decimal point, no exponent%f
123.46Default width, precision 2%.2f
␣␣123.46Width 8, precision 2%8.2f
123.456Exponent as needed, necessary digits only%g

This is end of part 1, we have gone through, how to start a project in golang then variable and data types. Next we will look into functions and slices and in last part we will go into structs and how to use some of the OOPs concepts you learned in Golang.

Did you find this article valuable?

Support Ratnadeep Bhattacharyya by becoming a sponsor. Any amount is appreciated!