Golang: First look


Features of Golang:

  1. Compiled language. So, you can measure performance and do memory profile. It generates machine code that will run on the processor.
  2. Garbage collected. Usually system level langauges are not garbage collected, but Go is. Also note that, Go garbage collector is latency free. So, garbage collector runs without any speed bumps.
  3. Language level support for concurrency strategy known as communicating sequential processes aka Actor model.
  4. It’s not a C derivative language. It’s a static language but with the ease of dynamic language

Interesting notes

  • Like Swift playground in Xcode, you can try out go code in https://play.golang.org/
  • Go doesn’t have method overloading.
  • Function name starts with Uppercase are going to be exported (public)
  • Go packages can be directly imported from URL inside code
  • You can’t write curly braces in separate line, like C#. Yey!

Installation

Install Go and make sure to define GOROOT and GOPATH

export GOROOT="/usr/local/go"
export GOPATH="/Users/USERNAME/GoWorkspace/"

First Program

package main

import (
	"fmt"
)

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

#1. package declaration is required and it is called module. “main” package denotes entry point
#7. You have to maintain the signature
func main() {
}

as it is the execution point

To run,
go run main.go
To build and make executable file,
go build main.go

Variable

package main

import "fmt"

func main() {
	// declare multiple variable
	var a, b int

	// initialize multiple variable
	var c, d int = 1, 2

	// omit data type
	var e, f = 4, 5

	// infer type
	var g, h = 6, false

	// declare and init together
	message := "Hello"

	// by default, un-initialized value is 0
	fmt.Println(a, b, c, d, e, f, g, h, message)
}

/*
Output:
0 0 1 2 4 5 6 false Hello
 */

Constant

package main

import (
	"fmt"
)

const (
	FIRST_CONSTANT = "Hello"
)

var (
	globalVar = 5
)

func main() {
	fmt.Println(FIRST_CONSTANT)
	fmt.Println(globalVar)
}

/*
Output
Hello
5
 */

Init function

If you write init function it will run the first time the module is referenced. It will run before the main function and after all the instance variable is initialized.

package main

import (
	"fmt"
)

var (
	globalVar = 5
)

func init() {
	globalVar = 6
}

func main() {
	fmt.Println(globalVar)
}

/*
Output
6
 */

Unused imports

Unused imports will give you error. For example, if you declare “fmt” package but do not use it, you will get error,

package main

import (
	"fmt"
)

var (
	globalVar = 5
)

func main() {
	println(globalVar)
}

// tmp/sandbox540429761/main.go:4: imported and not used: "fmt"

Installation

Download and install Go from here, https://golang.org/

Update your .bash_profile in MacOS or .bash_rc in Linux

export GOROOT="/usr/local/go/bin/go"
export GOPATH="/Users/<username>/GoWorkspace"
export PATH=$PATH:$GOROOT

Install Sublime and then Sublime package control,
https://packagecontrol.io/installation

Install GoSublime
https://github.com/DisposaBoy/GoSublime

Verify installation

Create a file named main.go

package main

func main() {
	println("Hello Go")
}

Open terminal and go to the file directory and run

~$ go run main.go
Hello Go

Data types

package main

func main() {
	var anInt int = 5

	// witout the . (dot) value will be inferred as int
	var aFloat float32 = 3. 

	// shorthand to declare and initialize
	aString := "Hello there" 

	println(anInt)
	println(aFloat)
	println(aString)
}

Constants again

package main

const (
	first = iota // auto incrementing number
	second
	third
)

func main() {
	println(first)
	println(second)
	println(third)
}

/*
0
1
2
*/
package main

const (
	first = 1 << iota
	second
	third
)

func main() {
	println(first)
	println(second)
	println(third)
}

/*
1
2
4
*/

Collections: Array

package main

import (
	"fmt"
)

func main() {
	anArray := [...]int{3, 6, 9, 12}

	fmt.Println(anArray)
	fmt.Println(len(anArray))
}

/*
[3 6 9 12]
4
*/

Collections: Slice

package main

import (
	"fmt"
)

func main() {
	anArray := [...]int{3, 6, 9, 12}

	aSlice := anArray[:]        // all elements
	aSlice = anArray[1:]        // except first element
	aSlice = append(aSlice, 15) // appending 15

	fmt.Println(aSlice)
	fmt.Println(len(aSlice))

	newSlice := []float32{1., 2., 3.}
	fmt.Println(newSlice)

	anotherSlice := make([]int, 20)
	anotherSlice[0] = 5
	anotherSlice[1] = 10

	fmt.Println(anotherSlice)
}

/*
[6 9 12 15]
4
[1 2 3]
[5 10 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
*/

Loop

package main

func main() {
	for i := 0; i < 5; i++ { 	} 	hello := 0 	for { 		hello++ 		if hello > 5 {
			break
		}
	}

	list := []string{"hello", "world", "go"}

	for index, value := range list {
		println(index, value)
	}
}

Functions

package main

func main() {
	param := "Hello there"
	helloGo(¶m)
	println(param)
}

func helloGo(param *string) {
	*param = "Hello Go"
}

func helloGo2(params ...string) {
	// variable argument function aka variadic parameter
}

Multiple return values

package main

func main() {
	result := add(1, 2, 3, 4)
	println(result)
	a, b := andAndLen(1, 2, 3, 4)
	println(a, b)
	len, sum := andAndLen2(1, 2, 3, 4)
	println(len, sum)
}

func add(nums ...int) int {
	ret := 0
	for _, num := range nums {
		ret += num
	}

	return ret
}

func andAndLen(nums ...int) (int, int) {
	ret := 0
	for _, num := range nums {
		ret += num
	}

	return len(nums), ret
}

func andAndLen2(nums ...int) (length int, sum int) {
	for _, num := range nums {
		sum += num
	}

	length = len(nums)

	return
}

Struct

package main

import (
	"fmt"
)

func main() {
	aVar := aStruct{}
	aVar.aField = "hello"

	anotherVar := aStruct{"hi"}
	println(anotherVar.aField)

	// creates the object in heap
	yetAnotherVar := new(aStruct)
	yetAnotherVar.aField = "hola"

	fmt.Println(aVar)
}

type aStruct struct {
	aField string
}

/*
hi
{hello}
*/

Constructor

package main

import (
	"fmt"
)

func main() {
	aVar := newAStruct()
	aVar.aMap["foo"] = "bar"

	fmt.Println(aVar)

}

type aStruct struct {
	aMap map[string]string
}

func newAStruct() *aStruct {
	ret := aStruct{}
	ret.aMap = map[string]string{}

	return &ret
}

Method

package main

func main() {
	mp := msgPrinter{"foo"}
	mp.printMsg()
}

type msgPrinter struct {
	msg string
}

func (mp *msgPrinter) printMsg() {
	println(mp.msg)
}

Go routine

package main

import (
	"runtime"
	"time"
)

func main() {
	runtime.GOMAXPROCS(4)

	go printMsg()
	println("after all print")
	time.Sleep(100 * time.Millisecond)
}

func printMsg() {
	for i := byte('a'); i <= byte('z'); i++ {
		go println(string(i))
	}
}
Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s