Go : Just Go for it

Golang is an open-source, light-weight procedural programming language, developed in 2007 by Robert Griesemer, Rob Pike, and Ken Thompson at Google but launched in 2009 as an open-source programming language. Go is statically typed and compiled language, it is fast and easy to learn. Go is used for building servers and web apps.

Why Go lang?

1. Easy to learn

Since the syntax of Go lang is somewhat similar to the C language, it is easy to pick up, especially for C-style or Java programmers, syntax is very similar to how we speak.

var a int = 25

So how we speak the same is, what we want to create? a variable, keyword is var, what do we name it? in this example it is a, what is the type of it? which is int.

Similar syntax for other things also, we will see those as well.

Go has extensive documentation available to understand the concepts from scratch.

2. Concurrency

Go lang has a concept of Goroutine, which is a lightweight thread managed by Go runtime. It has growable segmented stacks, which means it will use more memory only when needed. Goroutines have built-in primitives to communicate safely between channels. When sharing data structures, it allows you to avoid having to resort to mutex locking.

3. Networking

Go can have high-quality parsing libraries that are easy to plug into other libraries. It is excellent for writing networking applications, like writing TCP or HTTP servers at the production level.

4. Speedy Execution

Unlike Python, GO is a compiled language and it is very fast.

5. Libraries

There are many libraries that you can make use of, which have built-in functions that you have to mention in import(package/packages) and make use of it.

Basics of Go

Main function is the entry point of every Go program, programs start executing from main(), there is also a function named init which executes even before main(), so if there are any initializations (for package variables) to be done we can do it in the init function.

First program in Go
package main

import "fmt"

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

package main instruct the compiler to make executable out of this and not a library.

import is used to import any packages either self defined or existing.

We are importing the fmt package which has functions like PrintlnPrintf, Sprintf.

main() is the entry point of our program from there the execution starts.

Println is a function that outputs to the console.

Output of the program is :

Hello, World

Example of init:
package main

import "fmt"

func init() {
	fmt.Println("Inside init")
}
func main() {
	fmt.Println("Inside main")
}
Output of the program:

Inside init

Inside main

Variables

There are basic variables such as int, float, complex, string, and bool.

we can define our own variables using type keyword.

syntax to declare a variable:
var variable_name variable_data_type =some_value
Shorthand declaration
variable_name :=some_value
Example:
package main

import "fmt"

func main() {
	var a int = 9
	b := 65
	fmt.Println("Values of a:", a, "value of b:", b)
}

Example of bool
package main

import "fmt"

func main() {
	var a bool = true
	b := false
	c := a && b
	d := a || b
	fmt.Println("value of a :", a, " value of b: ", b)
	fmt.Println("c: ", c, " d: ", d)
}
Example of float
package main

import "fmt"

func main() {
	a := 5.56
	b := 6.23
	fmt.Printf("type of a :%T b :%T\n", a, b)
	sum := a + b
	fmt.Println("Sum a,b :", sum)
	diff := a - b
	fmt.Println("Diff a,b :", diff)
}

Multiple variable declarations

we can declare more than one variable on one line, given all are of same type

Syntax:
var variable_name,variable_name data_type = some_value
Example:
package main

import "fmt"

func main() {
	var a, b int = 3, 4
	var c, d, e = 1, "Hello Go", 2.5
	fmt.Println("Val of a: ", a, "Val of b: ", b)
	fmt.Println("Val of c: ", c, "Val of d: ", d, "Val of e: ", e)
}

Constants

Constant can be declared using const keyword, Constants are evaluated at compile time so we should not assign function to a const.

Syntax:
const variable_name data_type = some_value
Example:
package main

import "fmt"

func main() {
	const a int = 9
	fmt.Println("Values of a:", a)
}

Using type to create custom variables

Syntax:
type custom_variable_name variable_data_type
Example:
type Entity string

Arrays

Arrays are value type and not reference type in Go

syntax:
var arr [length]data_type
Example:
package main

import "fmt"

func main() {
	arr := [3]int32{1, 2, 3}
	fmt.Println("array arr: ", arr)
	fmt.Printf("type of arr: %T\n", arr) //Type of an array is size and data
	arr1 := arr
	fmt.Println("array arr1:", arr1)
	fmt.Println("If arr1 equals to arr: ", arr == arr1) //for array to be equal their type and elements should be same
	arr[2] = 24
	fmt.Println("array arr: ", arr)
	fmt.Println("If arr1 equals to arr: ", arr == arr1) //for array to be equal their type and elements should be same
	arr2 := [3][4]int{{1, 2, 3, 4}, {3, 2, 1}}
	fmt.Println("two D array arr2:", arr2)
}

Here // is used, it is used for single line comments, compiler will consider it as comment.

Slices

Slice is reference type, meaning change reflects.

syntax:
variable_name := make([]data_type,length,capacity)

Slices come with length as well as capacity.

Capacity is what we can append the slice till appending to slice beyond capacity then the underlying array changes meaning change does not reflect.

Example:
package main

import "fmt"

func main() {
	arr := [10]int32{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
	s := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} //basic syntax of slice
	slice := arr[:]                           // 0 to len-1
	slice1 := arr[0:]                         // 0 to len-1
	slice2 := arr[:6]                         //0 to high-1
	slice3 := arr[3:8]                        //3 to 8–1
	fmt.Printf("slice length :%d, slice capacity :%d\n", len(slice2), cap(slice2))
	slice2 = arr[:8]                                                               //resizing slice
	fmt.Printf("slice length :%d, slice capacity :%d\n", len(slice2), cap(slice2)) //after resizing
	fmt.Println(len(arr))
	fmt.Println("slice :", slice)
	fmt.Println("s :", s)
	fmt.Println("slice1 :", slice1)
	fmt.Println("slice2 :", slice2)
	fmt.Println("slice3 :", slice3)
	slice[0] = 9
	fmt.Println("slice after reassignment as it is reference type :", slice) //making a slice using make function
	slice4 := make([]int, 5, 10)
	fmt.Println("slice4 :", slice4) //default value of slice is 0//making slice a nil slice
	var slice5 []int
	fmt.Println("slice5 :", slice5)
}

Struct

We can also create a struct in Go, as follows.

syntax:
var variable_name struct{}
Example:
var person struct {
	name string
	age  int
}

Map

Map holds key-value pair.

Syntax:
variable_name:=make(map[key-type]value-type)
Example:
mp:= make(map[string]int)

Adding to a map

mp[“abc”] = 3

Length of map

len(mp)

Getting from a map

a:= mp[“abc”]

Deleting from a map

delete(mp,”abc”)
Example:
package main

import "fmt"

func main() {
	mp := make(map[string]int)
	mp["Avinil"] = 4
	mp["Aniket"] = 2
	fmt.Println("my first map in Go: ", mp)
	fmt.Println("Size of map mp :", len(mp))
	fmt.Println("Getting an element from a map :", mp["Avinil"])
	delete(mp, "Avinil")
	fmt.Println("map :", mp)
	_, prs := mp["Avinil"]
	fmt.Println("prs :", prs)
	mp1 := map[string]int{"Avinil": 1, "Aniket": 2}
	fmt.Println("map mp1 :", mp1)
}

Pointers

Go supports pointers, allowing you to pass references to values and records within your program, Go does not support pointer arithmetic.

Declaring a pointer

Syntax:
var variable_name *data_type

Example:

package main

import "fmt"

func main() {
	a := 5
	var ptr *int = &a
	ptr1 := &a
	fmt.Println("val of a: ", a)
	fmt.Println("val of a using Pointer: ", *ptr) //using Pointer
	fmt.Println("address of a: ", &a)
	fmt.Println("address of a using Pointer: ", ptr1) //using Pointer
}

Loop

There is only one loop in Go, which is for.

syntax:

for{}
Example:
package main

import "fmt"

func main() {
	for i := 0; i <= 5; i++ {
		fmt.Println(i)
	}
	n := 2 //while like for
	for n < 5 {
		n *= 2
	}
	fmt.Println(n)
	//infinite loop
	// for {
	// fmt.Println("Hello Go")
	// }
}

Functions

Functions are important in procedure oriented programming language, we can declare a function using the func keyword. Functions can be returned from a function as well as they can be passed as a parameter.

Syntax:
func function_name(input_parameters) (output_parameters){}
Example
package main

import "fmt"

func calculatePrice(price, items int) int {
	return price * items
}
func main() {
	var price, items int = 90, 6
	fmt.Println("Total price of :", items, " items ", " is: ", calculatePrice(price, items))
}

Variadic functions

These functions can accept variable number of input parameters.

Syntax:
func function_name(parameter_name …data_type) (parameter_name){}

Example:

package main

import "fmt"

func main() {
	fmt.Println(variadicFunction(1, 2, 3))
	fmt.Println(variadicFunction(1, 2, 5, 3, 7))
	fmt.Println(variadicFunction(11, 2, 43, 77, 120))
}
func variadicFunction(nums ...int) int {
	var total int = 0
	for _, n := range nums {
		total += n
	}
	return total
}

Anonymous function

It is an unnamed function, which can be executed there itself.

Example:
package main

import "fmt"

func main() {
	func() { // this function is anonymous function
		fmt.Println("Inside anonymous function")
	}() //immediate execution as we are calling it there itself
}

I have not given output of all the programs, and it is intentional, you can guess the output or/and try on your own for better understanding.

Suggestions are always welcome. This is part one of the Go lang concepts that I have learned, in addition to this there will be some more concepts that I will be posting soon.

Thanks for reading, hope you find it helpful.

One thought on “Go : Just Go for it

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.