I have been learning and playing around with GoLang lately and it seem to be fun. At first being a Java developer it looks weird and complex, but once you start playing around it is quite fun.
Why did I start learning Go ? – I read a lot about its features like being simple, fast, having very good support for concurrency, ability to build applications with high concurrency in less time etc. Also many people have started using it for many production level applications which speaks good things about the language. This brings enough motivation to start playing with the language and see how it can make a difference.
Installing Go : Follow this to download and install Go.
Let’s jump on to the basics of Go :
Package declaration :
// A package declaration starts every go source file. // main - distinguishes an executable from a general library. // For executables : package main // For general library : package mylib
Import libraries :
// For single import import "fmt" //Go standard library // For multiple imports import ( "fmt" i "io/ioutil"//I/O utilities library with an alias i "math" ) // Once you do this, you can use the packages in the libraries. //For example to print a line use fmt. fmt.Println("Hello geeks!")
Variable Declaration :
// a simple int variable var myVar int /* Important to note that variables must be declared before use. type of variable comes after the variable name. */ //assignment myVar = 4 // Declare, assign and infer type in one statement // use := myNewVar := 6 // declares myNewVar, assigns a value of 6 and infers // type as int
Function declaration :
//Declaring a function is simple and similar to other languages func main() { fmt.Println("Hello geeks!") anotherFunc() //Call another functions within same package } func anotherFunc() { // Some function body }
Functions with parameters and return types :
// Again types at the end func multiply(x,y int) (result int) { return x*y }
A really interesting thing is that you can return multiple values from functions :
func mutilplyAndSum(x,y int) (multiply,sum int) { return x*y, x+y // Return two values. }
More data types :
//float64 - 64bit floating point number floatingNum := 7.6990 // String str := "Hello Geeks!" // Unsigned integer var unsignedInt uint = 8
Arrays: Have fixed size
var arr [5]int // An array of fixed size 5 initialised to 0 arrNew := [...]int{8,2,4,1,0} // An array of fixed size 5 initialised
Slices: Dynamic size (like ArrayList in Java)
mySlice := []int{4,2,1} //Slice of size 3 with values myNewSlice := make([]int, 6) // Allocates a slice of 6 integers, intialised //to 0
Appending Elements to Slice :
slice := []int{1,3,4} slice = append(slice, 5, 6, 7) //Adds 3 elements . New slice length is 6 // Appending another slice to a slice slice = append(slice, []int{7,8,9}...)
Maps in Go:
// creates a map of string->int myMap := map[string]int{"hello":1, "geek" :2} //Putting a value ? Its simple myMap["narrator"] = 3
Branching / Flow Control in Go :
// if else conditions - conditions do not need () unlike Java if true { fmt.Println("Hello Geek!") } else { fmt.Println("Hello World!") } // Switch case switch a { case 0: case 1: case 3: default: // optional }
Looping in Go :
There is only for loop in Go. No other loop 🙂
// Approach 1 for i := 0; i < 10; i++ { fmt.Println("Hello Geek No:", i) } // Another approach for { //Infinite loop } // Iterating over a map for k,v := range map[string]int{"hello" : 1, "geek" : 2, "narrator" :3} { fmt.Println("key=%s, value=%d\n", k, v) }
Closures : (Function literals)
// func assigned to a name isTrue := func() bool { if i > 10 //assuming i is defined } // To call this fmt.Println("isTrue : ", isTrue())
Structs in Go :
//This creates a simple structure with two fields xCor and yCor type Coordinate struct { xCor, yCor int }
Error Handling in Go :
// err is returned from the calls which can be checked if _, err := strconv.Atoi("ajksjk"); err != nil { fmt.Println(err) }
Multithreading/Concurrency in Go :
// You can make channels using make function. //What are channels ? A communication object which is concurrency safe // <- is a send operator, which can be used to send something to the channel // for ex: channel := make(chan int) // makes a channel which accepts int values conurrently // Starting new threads(goroutines) go inc(0,channel) go inc(100,channel) go inc(-190, channel) // inc is a function which increments the value and sends to the // channel func inc(x int, channel chan int){ channel <- x+1 } // Read response from the channel fmt.Println(<- channel, <- channel, <- channel) // <- acts as a receive operator
Important differences that I noted :
- No semicolons.
- No “()” in if statements.
- datatype on the right .
- Nice and easy concurrency using goroutines. No boiler plate required.
- Support for channels for concurrent use.
- Functions can return two values instead of creating a class or struct first, which is good.
- Functions with first letter in Upper case, are exposed (Public) rest all are private. So there is no default, protected etc.For example Println() function is an exposed function of fmt library. if p was lowercase it would have been private to the package.
A nice way to quickly get started : PLAYGROUND
I will add more examples and complex functions in coming days.
Go and Enjoy programming with Go.
Cheers,
Kaivalya