Go Introduction – Special for Lazada Platform team



Go Introduction – Special for Lazada Platform team

0 1


go_intro


On Github yvasiyarov / go_intro

Go Introduction

Special for Lazada Platform team

Created by Yuriy Vasiyarov

Go is...like C

  • Low level

  • Compiled

  • Not object oriented

  • Memory efficient

But Go is not C...Go is better!

  • Garbage collector

  • Go routines

Go memory model

...is very efficient

  • bool variable - takes only 1 byte

  • int variable - takes only 4 bytes

  • float variable - takes only 8 bytes

  • array of 10 bool - takes exactly 10 bytes

  • struct which consist of 3 integers - takes exactly 12 bytes

Just like in C

compare it with PHP/Ruby/etc...

Value types VS reference types

  • bool, int, float, STRUCT - are value types

  • slices,maps,channels, interfaces - are reference types

You should think twice before pass struct by value

in most cases you should use pointer instead

Slices

slice := []int{1,2,3,4, 5, 6, 7, 8, 9, 10}

unsafe.Sizeof(slice).... 12 bytes!

WHY ??

Because slice != array

Slice is reference to array

On low level slice is

            struct {
              storage - pointer to underlying array
              length - length of slice
              capacity - slice capacity(length of underlying array)  
            }
          

Slice storage managed by Go runtime

  • several slices can reference to same array

  • Go runtime count refernces to underlying array

  • Go can expand underlying array(append())

Maps

  • Map is hash table (like "array" in PHP)

  • Map always expands automatically

  • Maps are not safe for concurrent usage

Interfaces

  • Interface - is not pointer

  • Interface used when you dont know type at compile time

  • a := []interface{} - slice which can contain data of any types

Interfaces on low level

http://research.swtch.com/interfaces

Channels

Goroutines

  • Goroutines are truly parallel

  • Goroutines are easy to use

  • Goroutines are lightweight

  • ...same as in Erlang/Haskell/...

  • Goroutines are not OS threads

Go scheduler

  • Automatically create/destroy OS threads

  • Can utilise any number of CPU's - but use only 1 by default

  • Go scheduler automatically distribute goroutines across available CPU's

Goroutines sometimes too powerful...

Don't shoot into your legs!

Race conditions

  • Very hard to debug/fix

  • Atomic primitives are safe for concurrent usage

  • All other data must be protected by mutexes/channels

  • Go has build in race detector! http://blog.golang.org/race-detector

Questions ?