SlideShare a Scribd company logo
1
Go Language
Romin Irani | Jan 31 2015 | @iRomin | romin.k.irani@gmail.com
Objectives
 What is the Go Language all about?
 Whirlwind Tour of the Language
 See lots of code samples
 Hopefully … make you code a little bit too in
this session
 Get you interested enough to learn more about
Go!
2
Any Prerequisites?
Hands-on Exercises
https://goo.gl/eV2L7
O
3
Why use Go?
 Modern
 Popular
 Simple
 Fun
 Do More With
Less
4
Go Language History
 Started in 2007 @ Google
 Initial Release in 2009
 Rob Pike, Robert Griesemer, Ken Thompson
 Designed to overcome issues with using Java,
Python and other languages across large code
base
 Systems Language  General Purpose
Language
 Current @ 1.5
 Version 1.6 to be released in Feb 2016
5
Go Features
 Similar to C Language in Syntax
 Case sensitive
 Only 25 keywords
 Cross Platform Binaries
 Compiled Language
 Statically Typed
 Solid and comprehensive Standard Packages
 Object Oriented Features
 Composition over Inheritance
 Open Source
6
Popular Projects
 Popular with Infrastructure Software Companies
 Popular Projects
 Docker
 CoreOS: etcd, rkt
 Kubernetes
 InfluxDB, RethinkDB
 Hugo
 Consule
 And more
 Great choice for a modern, general purpose
language
7
Go Home Page
www.golang.org
8
Go Playground
 Go Playground :
http://play.golang.or
g
 Excellent way to get
familiar with syntax
 Run Go code in the
cloud
 Save and Share Go
Snippets
 Some restrictions
9
First Go Project
 We will be creating a new Project
 Let us call it helloworld
 Create this project folder in the GOPATH root
i.e. $GOPATHhelloworld
 Open Atom Editor. Add the
$GOPATHhelloworld Project Folder
 Create a new file named hello-world.go
10
Hello World in Go
11
Running our Application
 go run <filename>
 go run hello-world.go
12
Built-in Types
13
 bool
 string
 int int8 int16 int32 int64
 uint uint8 uint16 uint32 uint64 uintptr
 byte // alias for uint8
 rune // alias for int32
// represents a Unicode code point
 float32 float64 complex64 complex128
Variable Declaration
 Use the var keyword
 Format
var <variablename> <type>
var <variablename> <type> = <initialvalue>
 Examples:
var phoneModel string = “Samsung S5”
var osName string = “Android”
var price float32 = 40000.0
14
Variable Declaration
 Use the block declaration to combine multiple
variables
var (
phoneModel string = “Samsung S5”
osName string = “Android”
price float32 = 40000.0
)
15
Variable Declaration
 Declare multiple variables of the same type as
follows:
var firstName, lastName string = “A”, “B”
var i,j int, k string =10,20,”Hello”
 If initializer is present, the type can be omitted:
var i,j = 10,20
16
Short Variable Declaration
 Use the := short assignment statement instead
of var
 The type is implicit i.e. determined by Go
 Available only inside a function and not at
package level
function main() {
price := 20.50
firstName := “Gopher”
}
17
Constants
18
 Declared with the const keyword
 They can be character, string, boolean or
numeric
 The scope depends on where they are defined
const tax_rate = 10.5
const city = “Mumbai”
Go : Zero values
19
 Every type has a Zero value
Zero Value Type
0 Numeric
false Boolean
“” String
nil Pointer, channel, struct, func,
interface, map, Slice
Go : Arithmetic Operators
20
Operator For?
+ Addition
- Subtraction
* Multiplication
/ Division
% Remainder
Go : Logical Operators
21
Operator For?
&& Boolean AND
|| Boolean OR
! NOT
== Test equality
Reference Types
22
 Go also has the following Reference Types
 Arrays
 Maps
 Slices
 Structs
 Channels
 We will look at them later
Hands On
Exercise #1 &
#2
23
Hello World: http://play.golang.org/p/achXqgsH1v
Variables, Constants: http://play.golang.org/p/dQuYzSgR0P
What are functions?
 Functions are the building blocks of Go
programs
 An independent section of code
 Also known as procedure or subroutine
 Can take input parameters
 Can return single or multiple return values
 Variable number of arguments
 Functions are first class citizens in Go. They
can be passed around as any other value.
 Anonymous Functions
24
Writing a function
 You have already seen the main() function in
action
25
Writing a function
 Define your function by specifying the following:
func funcname() {
}
 This is the simplest way to define a function.
 It does not take any input parameters
 It does not return any values
 E.g.
func sayHello() {
fmt.Println(“Hello”)
}
26
Function with input parameters
 Define your function by specifying the following:
func funcname(param1 type, param2 type) {
}
 This function takes two input parameters
 It does not return any values
 E.g.
func sayHello(firstName string, lastName string, age
int) {
fmt.Println(“Hello”,firstName,lastName,”You
are”,age,”years old”)
}
27
Function with input parameters
 If multiple parameters are of same type, you
can use a short-hand way of declaring:
func funcname(param1,param2 type1, param3
type2) {
}
 f1(num1,num2 int, name string)
 f2(num1 int, firstname, lastname string)
28
Function with return values
 A function can return a value : single or multiple
func funcname(param1,param2 type1, param3 type2)
(return value types) {
}
 f1(num1 int, num2 int) (int) { return 0}
 f2(num1 int, firstname, lastname string) (int, string) {
return 1, “Hello”}
 f3(num1 int, num2 int) (int, bool) { return false}
 f4(num1 int, num2 int) (int, error) {
return 10, nil
//return -1, errors.New(“Some error”)
}
29
Variadic functions
 The last input parameter can contain multiple or variable number of
arguments
 They have to be of the same type
func funcname(param1 type1, …string) {
}
E.g.
func addNumbers(numbers …int) (int) {
}
Invoking it:
addNumbers(1,2,3,4,5)
addNumbers(1,2)
addNumbers(1,2,3,4,5,6,7,8,9,10)
30
Hands On
Exercise #3
31
http://play.golang.org/p/Z85-wKYlTI
for construct
 The only looping construct available in Go
 3 variants
 Single condition
 Classical For Loop : Initial Value, Final Value,
Increment
 Forever Loop
32
for : Single Condition
 for <condition> {
}
 Repeatedly executes the block while the condition
is true
Example:
for i < 3 {
fmt.Println(i)
i++
}
33
for : Classical Loop
for i := 1; i<=10; i++ {
fmt.Println(i)
}
 i:=1 , both declares, initializes the variable i
34
for : forever loop
for {
//do something
//if some condition met , then use break
}
 Similar to while true { … } in other languages
 Break out of the loop via the break or return
statement
35
Sample Code
 Go Playground:
http://play.golang.org/p/Z7bKxJ-ljK
36
if statement
 if statement is a condition followed by a block
 The block is executed only if the condition
evaluates to true
if <condition> {
//Some statements
}
if (sum > 100) {
…
}
37
if – else statement
if <condition> {
//block 1
} else {
//block 2
}
a:=1
b:=2
if a > b {
fmt.Println(“a is greater than b”)
} else {
fmt.Println(“a is less than or equal to b”)
}
38
If-else-if statement
if <condition 1> {
//block 1
} else if <condition 2> {
//block 2
} else if <condition 3> {
}
else {
}
39
switch statement
40
 switch statement can help in evaluating multiple
conditions
 The switch keyword is followed by an expression
and then multiple case statements, out of which
one will be executed
 The case data types could be int, float, string,
bool, etc. or even a complex expression / function
call
 Unlike other languages, there is no need for the
break statement after each case statement.
 A default case statement can be put too in case
none of the case conditions are met.
switch statement
switch i {
case 0: fmt.Println("Zero")
case 1: fmt.Println("One")
case 2: fmt.Println("Two")
case 3: fmt.Println("Three")
case 4: fmt.Println("Four")
case 5: fmt.Println("Five")
default: fmt.Println("Unknown Number")
}
41
switch statement
42
 Notice that there was no break statement
between the case statements
 If you want the code to fallthrough like it is in
under languages, use fallthrough
switch statement
43
 Use commas to separate multiple expressions
in same case statement.
switch i {
case 1,3,5,7,9: fmt.Println(“Odd")
case 2,4,6,8,10: fmt.Println(“Even")
default: fmt.Println("Unknown Number")
}
switch – without expression
44
 Eliminate the expression in switch statement.
This way, it can evaluate the case expression
switch {
case i < 10: fmt.Println(“Less than 10")
case i>=10 && i <=100 : fmt.Println(“Between 10 and 100")
case somefunc(i) > 200 : fmt.Println(“some statement”)
default: fmt.Println("Unknown Number")
}
Sample Code
 Go Playground:
 if / if - else: http://play.golang.org/p/bA0qVEx_eP
 switch :
 http://play.golang.org/p/wjwTpPLujg
 http://play.golang.org/p/lQQIiLzC1G
 http://play.golang.org/p/5rj5Y1hVPR
45
Hands On
Exercise #4
46
Arrays in Go
 Fixed length data type for holding elements of
same type
 Array can be of any types like int, string, struct,
pointers, etc
 Individual element of Array can be accessed
using integer index, using []. For e.g. num[0]
 Array index is 0 bound that if Array size is 5,
index ranges from 0 to 4
47
Declaring / Initializing Arrays
 var iArr = [5]int{}
 Creates an Array of length 5
 Each element of Array initialized to zero value i.e. 0
 iArr := [5]int {0, 1, 2, 3, 4}
Declare and initialize Array iArr of length 5, and with values 0, 1, 2,
3, 4
 iArr := [5]int {2: 20, 4: 50}:
Declare and initialize Array iArr of length 5, and will set value at
index 2 and 4 to 20 and 50 respectively
48
Accessing Array elements
 iArr[2], will access element at index 2 of Array
iArr
 iArr[3] = 10, will set 10 as value at index 3
 If index is more than length of Array, then an
error is thrown. For e.g. iArr[5] for an integer
Array of 5 elements will thrown the follow error:
“invalid Array index 5 (out of bounds for 5-element
Array)”
49
Iterating through Array
 Use the for or range statement
var numbers = [5]int{1,2,3,4,5}
for i:=0;i<5;i++ {
//numbers[i]
}
Use built-in len function for length of Array. For e.g.
for i:=0;i<len(numbers);i++ {
//numbers[i]
}
50
Iterating through Array
 for + range statement allows you to iterate over a collection.
 It provides both index and value of each item
var numbers = [5]int{1,2,3,4,5}
for index,value := range numbers {
fmt.Println(index,value)
}
Output:
0,1
1,2
2,3
3,4
4,5
51
Iterating through Array
 You can ignore any of the index or value , if not
interested
var numbers = [5]int{1,2,3,4,5}
for _,value := range numbers {
fmt.Println(value)
}
var numbers = [5]int{1,2,3,4,5}
for index, _ := range numbers {
fmt.Println(index)
}
Question : Why do you need to ignore any of the return values
that you are not interested in?
52
Array Sample code
53
1. Multiple Array examples
http://play.golang.org/p/p-eV7eZXYp
2. Pass by Value to function
3. Using for and range to iterate over
Array
http://play.golang.org/p/nN1Q3R0Z1X
4. A first look at Slices:
http://play.golang.org/p/WarnTGxDaE
Arrays : Practical Considerations
 Fixed in Length
 Arrays are passed by value to function
 If the Array data is large in size ( or multi-
dimensional), impact memory and performance
 Go has a solution to addressing this that we
shall see in the next section : Slices
54
Slices - Overview
 Slice data type is similar to an Array
 Just like an Array, a Slice too holds elements
of same type
 It does not have a fixed length
 A Slice allows for dynamic expansion and
shrinking of the Array
 It is an abstraction built on top of an Array type
and shares same memory as that of
underlying Array
55
Declaring / Initializing
 Use make function for creating a Slice
make([]T, length, capacity)
 T is the type of element to hold
 length, of Slice to be created. It is mandatory to
specify length
 capacity, of Slice to be created. It is optional to
specify capacity. In case if not specified , capacity
is assumed to be same as length
56
Declaring / Initializing
 Slice := make([]int, 5, 10)
This will create Slice of type int, of length 5
and capacity 10.
 Slice := make([]int, 5)
This will create Slice of type int, of length 5
and capacity 5.
57
Declaring / Initializing
 Slice is used in same way as Array.
Slice[0] = 1
Slice[1] = 2
Setting values at index 0 and 1 into Slice
 Use function len to find length of Slice
 Use function cap to find capacity of Slice
58
append function
 It is always recommended to use append
method while adding value(s) to Slice
 Function append, internally checks if value to
be added in more than the length, it will create
new Array using capacity and add new value.
 Call to append always returns new Slice
59
Slicing Arrays
 So far we created Slice using make function,
which also creates underlying Array for Slice
 But we can also create Slice on top of Array
Let us assume Array i := [5] int {1, 2, 3, 4, 5}
 Slice := i[1:3]
This will create Slice over Array i, using values starting
from index 1 to 3 i.e. 2, 3, 4.
 Slice := i[:]
This will create Slice covering entire Array i.e.
from index 0 to 4.
60
Declaring / Initializing
 Slice := [] int {1, 2, 3, 4, 5}
Creating Slice in same way as Array. But here
we don’t specify length in the preceding
square brackets
 Empty Slices:
 Slice := []int {}
 Slice := make ([]int, 0)
 Creating new Slice from Slice
 Slice2 := Slice[1: 3]
61
Slice Representation
62
Pointer
(0)
1
(1)
2
(2)
3
(3)
4
(4)
5
Slice := [] int {1, 2, 3, 4, 5}
Pointer
new_Slice := Slice[2 : 4]
Key points while using Slices
 Slice is a reference to an Array
 All the Slices on an Array shares same
memory as that of Array
 Can create more than one Slice on same
underlying Array
 Any changes made to one Slice will be
reflected in other Slices and in Array too
 Useful to use a slice instead of entire Array in
case of large amount of data
63
Iterating over Slices
 Use the range keyword
numbers := []int{100, 200, 300, 400, 500}
for index, value := range numbers {
fmt.Println(index, value)
}
 Go Playground
http://play.golang.org/p/P_nSXzxAC1
64
Examples
 Slice from make function
http://play.golang.org/p/sGQ2WOT1S3
 Slice from Literal
http://play.golang.org/p/R60h2f2xt9
 append, len and capacity functions
http://play.golang.org/p/gUPJNCelX0
 Slices are passed by value to functions
http://play.golang.org/p/nluakS7P-s
 Multiple Slices work over the same array
http://play.golang.org/p/BsHTCliECU
 Iterating over Slices
http://play.golang.org/p/6Ax7L6Ud7E
65
Map
 Only key/value paired collection in Go
 Map is an unordered collection i.e. order in
which key/value returned is not always the
same
 Map, uses a hash table for storing key/value
66
Declaring/Initializing
 Use function make for creating Map
make(map[key type]value type)
In make function, use keyword map, specify
the type to be used as key in square brackets
and type to be used as value outside square
bracket
m := make(map[int]string)
This will create a Map, with key as int and
value as string
67
Declaring/Initializing
 We can also create without using make function
m := map[int]string{}
 It is also possible to declare and initialize map in
one statement
m := map[int]string {
1: “One”,
2: “Two”,
3: “Three”,
}
68
Using Map
 Write to map
m[4] = “Four”
This will add, key 4, and assign “Four” as it is value
 Read from map
s := m[2]
Will return value for key 2 i.e. “Two”.
 In case if key is not present in map, it will return
zero value for type of value.
In our case if we use m[100] and since key 100 is
not present in map, empty string will be returned
as for string, empty string is zero value
69
 Function len, can be used to determine
length/size of the map
 Function delete, to be used to deleting
key/value from map
delete(m, 1)
Will delete key/value pair whose key is 1 from map
m.
If m is nil or key is not present in map, delete will be
no operation
70
Using Map
Using Map
 i, ok := m[1]
Here 2 values will be returned, 1st the value for key and
2nd boolean to indicate if key/value exists
 i := m[100]
Here only value for the key will be returned
 _, ok := m[100]
This can be used to check if key/value exists. We
have used blank Identifier (Underscore) as 1st
value to skip it
71
Iterating a Map
m := map[int]string{
1: “One”,
2 : “Two”,
3: “Three”,
}
We can iterate over map using range as shown
below
for k, v : range m {
fmt.Println(“Key :”, k, “ Value :”, v)
}
Two values are returned, 1st is key and 2nd is value.
72
Examples
 Creating a Map
http://play.golang.org/p/8P-lR6XXe0
Accessing Map (Example 1)
http://play.golang.org/p/nSh2EpFsGa
 Accessing Map (Example 2)
http://play.golang.org/p/VQ0EZJoCWt
 Function
http://play.golang.org/p/YNtjqHYCbd
73
Hands On
Exercise #5
74
Structs
 Struct is user defined data type
 Struct, as the name says is a structure used
for logical grouping of fields/property
 If you are familiar with OO language Java, you
can co-relate it with class
 A Struct, like most other data types when
passed as parameter to function is passed by
value
75
Declaring/Initializing
 Following is the template used for declaring a struct
type <name> struct {
}
keyword type is used to define a new type followed with
name of the struct, followed by keyword struct to indicate
that type is a struct
 Example
type User struct {
FirstName string
LastName string
Age int
}
76
Declaring/Initializing
 Just like any other data type, A Struct too can be
declared and initialized in two steps
var u User
This will declare variable of u of type struct User
and initialize it to zerovalue.
 We can do declaration and initialization in one
statement as shown below:
u := new(User)
Using new will allocate memory and return
pointer.
77
Declaring/Initializing
 We can pass values for each of the property to
be initialized at the time of creating an
instance of struct.
u := User{“Fn”, “Ln”, 50}
Here we have passed value as Fn, Ln and 50
which will be set to FirstName, LastName and
Age respectively.
 We can also specify property name explicitly in
case if we don’t wish to initialize all the
properties or if we don’t want to follow
sequential approach
u := User{Age: 50, FirstName: “Fn”}
78
Accessing
 We can access individual fields as follows:
u := User{Age: 50, FirstName: “Fn”}
Here we have not initialized LastName while
creating instance of User. Lets do it now:
u.LastName = “Ln”
 Use Println, for printing a Struct including all it
fields
fmt.Println(u)
This will print: {Fn Ln 50}
79
Nested Struct
type Address struct {
Building, Area, City, State, Country string
}
type User struct{
…
Address Address
}
u := User{Age: 50, FirstName: "Fn", LastName:"Ln"}
u.Address = Address{"building", "area", "city", "state", "INDIA"}
fmt.Println(u)
Output:
{Fn Ln 50 {building area city state INDIA}}
80
Struct : Receiver Methods
 Method is a function which is called upon instance. For example:
func (u User) isSeniorCitizen() bool{
isSrCitizen := false
if (u.Age > 60){
isSrCitizen = true
}
return isSrCitizen
}
Note the signature, we are preceding the function name with instance
of user. This is called as receiver and function is called as method
on User.
We can call this method as
u := User{Age: 50, FirstName: "Fn", LastName:"Ln"}
isSrCitizen := u.isSeniorCitizen()
81
Hands On
Exercise #6
82
http://play.golang.org/p/TRt2wOuBkT
Interfaces
 Interface is a way to add behaviour
 It is GoLang’s way to Polymorphism
 Interface is a contract that implementer needs to
fulfill
 Interface only defines methods with signature
without definition. Definition of methods is left up-
to implementer
 Interface leads to IS-A relationship
 You can add behaviour anytime by implementing
the Interface method. This is one of the nice
features of the language
83
Declaring
type <name> interface{
….
}
 Interface is declared using keyword type followed by
name followed by keyword interface
 Example
type Shape interface {
printArea()
}
Here we have declared interface of type Shape with
method printArea, which needs to be implemented by
implementer
84
Implementation
type Square struct {
side int
}
func (s Square) printArea
(){
fmt.Println(“Area of
Square”, s.side * s.side)
}
type Rectangle struct {
length, breath int
}
func (r Rectangle )
printArea(){
fmt.Println(“Area of
Rectangle”, r.length *
r.breath)
}
85
Implementation
func main(){
var s, r Shape
s = Square{5}
r = Rectangle{5, 4}
s.printArea()
r.printArea()
}
Output:
Area of Square 25
Area of Rectangle 20
We have created instance of Square and Rectangle and called printArea()
method on each of them.
86
Composition over Inheritance
 Go does not support inheritance
 It supports Composition via Type Embedding
 The design philosophy is to compose large
things from smaller components
 Composition over Inheritance helps to keep
the components loosely coupled even as
changes happen in the system + helps with
practical benefits of inheritance
87
Composition Example
 Composition is Go is done via Embedding the
Type
 The embedding struct gets the behaviour of
the embedded Type
 It can also access the struct elements directly
 It can override the behaviour of Embedded
Type if needed
 Though Composition is HAS-A , it is easier to
think of via IS-A
88
Interfaces + Type Composition
 You can define an Interface with its methods
 A Type (Struct) can implement it.
 You can then embed that type into any struct
 The Embedding Struct can override behaviour
if needed
 You can treat all the instances like IS-A type of
that particular Interface
89
Hands On
Exercise #7 &
#8
90
http://play.golang.org/p/toycLtAVxz
http://play.golang.org/p/i1Hpf2YA5-
Concurrency in Go
 What is concurrency?
 Concurrency v/s Parallelism
 Go routines
 Channels
 See sample code to see it work
91
Concurrency v/s Parallelism
92
Threads Anyone?
 Usually the execution of things concurrently is
done via an OS Thread
 On a single core CPU, only one thread can be
executing at a single time
 Threads are resource hungry and not that
lightweight
 Go does not use Threads
 Instead it uses go routines. Let’s check that.
93
go routines
 It is a light weight construct
 Go manages go routines
 Go routines are laid on top of threads
 Switching Threads is expensive
 Since multiple go routines could be in a
thread, switching is less expensive , therefore
less scheduling of Threads
 Faster startup times
 Communicating between go routines is via
Channels
94
Step 1 : Running Sequentially
 Go Playground
http://play.golang.org/p/OCHJV_xbI0
 This code invokes two functions , one after the
other
 There is no concurrency here
95
Step 2 : Introduce go routines
 Go Playground
http://play.golang.org/p/VZqsEyZbKG
 Simply put the keyword go before the function
call
 This will invoke the two functions concurrently
 Investigate : What happened?
 The program just exited
 This is because the main routine ended
immediately
 Suggested Fix : Maybe a timer ?
96
Step 3 : Introduce a Timer
 Go Playground
http://play.golang.org/p/dsno9tkdb0
 Introduced the time.Sleep method in both the
go routines so that each one of them allows
the other to run
 Additionally, we have put a longer timer in the
main routine so that there is sufficient time for
the go routines to complete
 Issue : We cannot keep playing with the timer
97
Step 4 : Introducing sync.WaitGroup
 Go Playground
http://play.golang.org/p/vavJveNVer
 Use a WaitGroup from sync package
 In the main routine, you can specify how many
go routines need to finish and one waits for
that
 Each go routine will indicate to the Wait Group
that is done
98
Go Channels
 Synchronization between go routines is done via
Channels
 A Channel can be thought of as a pipe that
connects the go routines
 Communication means “exchange of data”
 Channels take care of safely transmitting data
between the go routines and takes care of sync
operations
 Channels
 Buffered
 Un-buffered (Default)
99
Unbuffered Channel
 Creation
 ch1 := make(chan <datatype>)
 Writing to it : ch1 <- somedata
 Reading from it : somedata <- ch1
100
Unbuffered Channel
 Sender go routine will write data to the Channel
 Receiver go routine will wait on the Channel
 The Sender blocks till the Receiver gets the data
 The Receiver blocks till it receives the data
 Unbuffered Channel = Combines Communication with
Synchronization
101
Unbuffered Channel : Example
 Go Playground
http://play.golang.org/p/T8_4wz0fjw
 Main routine (RECEIVER) waits for a message
on the channel
 go routine (SENDER) – completes it’s task and
sends the message on the channel
 Try: Comment out the go f1() line and see
what happens when you try to run!
102
Buffered Channel
 Creation
 ch1 := make(chan <datatype>, size)
 Writing to it : ch1 <- somedata
 Reading from it : somedata <- ch1
103
Buffered Channel
 Sender go routine will write data to the Channel
 Receiver go routine will wait on the Channel
 The number of data blocks that can be written depend
on size
 The Sender go routine will not block after writing if the
buffer is still available
 The Receiver blocks till it receives the data
 Buffered Channel = Semaphore to limit throughput
104
Buffered Channel : Example
 Go Playground:
http://play.golang.org/p/ft03nGBshb
 Create a channel that accepts a string with a
buffer size of 2
 Main routine can wait for both go routines to
write to that channel
 Try : Uncomment the extra fmt.Println(<-
messageChannel) line
105
Buffered Channel : Example
 Go Playground:
http://play.golang.org/p/E3YikZ8UEv
 Channel that accepts string data type and
buffer size of 5
 Go routine sends the 5 messages and since it
is buffered, it is not blocked till the RECEIVER
gets it.
 Try : Introduce a timer if you want to sleep in
main routine and get the message later.
106
Understand Buffered Channels
 Go Playground:
http://play.golang.org/p/4Cbc7BfE7s
 The channel size is 5
 Notice how the go routine (SENDER) after
publishing 5 messages to the Buffered
Channel BLOCKS on the 6th message till the
RECEIVER starts reading from the channel
107
Go & Web Development
 Well suited to power web applications
 Sweet spot lies in creating Web APIs that can
be consumed by clients
 Core packages : net/http and html/template
 Web Frameworks:
 Martini
 Revel
 Others
108
 Powerful standard library to handle Request /
Response pattern
 The key component here is http.HTTPHandler
, which encapsulates the Request / Response
109
net/http Package
Various HTTP Handlers
 net/http provides several HTTP Handlers like
FileServer, NotFoundHandler, etc.
 Example : FileServer can be used for Static File
Serving
 http.FileServer(root FileSystem)
 Using http.ListenAndServe(port,handler) – we can
serve a static site
 Create the following file
http://play.golang.org/p/KyRDyXSpm7 in any
server and run the application there. Visit
localhost:8080 in your browser.
110
net/http Package
 We need to typically
map multiple URL
Paths to their HTTP
Handlers
 For e.g.
 /add -> Handler 1
 /edit -> Handler 2
 /delete -> Handler 3
 ServeMux in net/htttp
111
ServeMux
HTTP
Router
Handler 1
Handler 2
Handler 3
/add
/edit
/delete
Req
Res
p
Sample REST API
 Write a REST API for managing Employees
 To keep it simple, we will implement single
GET method call /employees to get all
employees
 Go Playground
http://play.golang.org/p/ged5yNOekx
112
HTTP Networking - Invoking REST API
 Use the net/http package
 Package http provides HTTP client and server
implementations
 Get, Head, Post, and PostForm methods to make
HTTP (or HTTPS) requests
 resp, err := http.Get("http://example.com/")
 resp, err := http.Post("http://example.com/upload",
"image/jpeg", &buf)
 resp, err :=
http.PostForm("http://example.com/form",
url.Values{"key": {"Value"}, "id": {"123"}})
113
Sample Code
 USD to INR Currency Rate
 Invokes a Currency REST API that returns JSON
Data
 http://apilayer.net/api/live?access_key=API_KEY&
currencies=INR&format=1
 Go Playground
 Step 1 : Retrieve JSON Data :
http://play.golang.org/p/H5-JX-1VEP
 Step 2 : Parse the JSON Data :
http://play.golang.org/p/Fp8S78V5UC
114
Several Other things …
 Unit Testing
 Go Tools
 Go Doc
 Take a look at :
https://github.com/avelino/awesome-go
115
Naming conventions
 Create the test file with name ending in
_test.go
 Inside the test file, each test is written in the
following form:
func TestXyz(t *testing.T)
 go build ignores the files ending in _test.go
 go test will take all the files ending in _test.go
 go help test
116
Go Documentation
 Go provides godoc tool for generating
documentation from source files
 You can use it to get information on packages
too
 See all documentation
godoc -http=:4000
 See specific documentation on a package
godoc math
 See specific documentation on a package +
function
godoc strconv Atoi
117
 Q & A
 Website : http://www.rominirani.com
 Email : romin.k.irani@gmail.com
 Twitter : @iRomin
118
Thank You
Ad

More Related Content

What's hot (20)

FTD JVM Internals
FTD JVM InternalsFTD JVM Internals
FTD JVM Internals
Felipe Mamud
 
Go. Why it goes
Go. Why it goesGo. Why it goes
Go. Why it goes
Sergey Pichkurov
 
Golang
GolangGolang
Golang
Software Infrastructure
 
Programming with Python - Basic
Programming with Python - BasicProgramming with Python - Basic
Programming with Python - Basic
Mosky Liu
 
The GO Language : From Beginners to Gophers
The GO Language : From Beginners to GophersThe GO Language : From Beginners to Gophers
The GO Language : From Beginners to Gophers
I.I.S. G. Vallauri - Fossano
 
Trivadis TechEvent 2016 Go - The Cloud Programming Language by Andija Sisko
Trivadis TechEvent 2016 Go - The Cloud Programming Language by Andija SiskoTrivadis TechEvent 2016 Go - The Cloud Programming Language by Andija Sisko
Trivadis TechEvent 2016 Go - The Cloud Programming Language by Andija Sisko
Trivadis
 
10 reasons to be excited about go
10 reasons to be excited about go10 reasons to be excited about go
10 reasons to be excited about go
Dvir Volk
 
Programming with Python - Adv.
Programming with Python - Adv.Programming with Python - Adv.
Programming with Python - Adv.
Mosky Liu
 
Learn python – for beginners
Learn python – for beginnersLearn python – for beginners
Learn python – for beginners
RajKumar Rampelli
 
Golang and Eco-System Introduction / Overview
Golang and Eco-System Introduction / OverviewGolang and Eco-System Introduction / Overview
Golang and Eco-System Introduction / Overview
Markus Schneider
 
OpenGurukul : Language : Python
OpenGurukul : Language : PythonOpenGurukul : Language : Python
OpenGurukul : Language : Python
Open Gurukul
 
Python basics
Python basicsPython basics
Python basics
RANAALIMAJEEDRAJPUT
 
OpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ ProgrammingOpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ Programming
Open Gurukul
 
EuroPython 2016 - Do I Need To Switch To Golang
EuroPython 2016 - Do I Need To Switch To GolangEuroPython 2016 - Do I Need To Switch To Golang
EuroPython 2016 - Do I Need To Switch To Golang
Max Tepkeev
 
Hands on Session on Python
Hands on Session on PythonHands on Session on Python
Hands on Session on Python
Sumit Raj
 
Python Basics
Python BasicsPython Basics
Python Basics
primeteacher32
 
Introduction to Clime
Introduction to ClimeIntroduction to Clime
Introduction to Clime
Mosky Liu
 
Go programming introduction
Go programming introductionGo programming introduction
Go programming introduction
Ginto Joseph
 
Os Goodger
Os GoodgerOs Goodger
Os Goodger
oscon2007
 
Python ppt
Python pptPython ppt
Python ppt
Rohit Verma
 
Programming with Python - Basic
Programming with Python - BasicProgramming with Python - Basic
Programming with Python - Basic
Mosky Liu
 
Trivadis TechEvent 2016 Go - The Cloud Programming Language by Andija Sisko
Trivadis TechEvent 2016 Go - The Cloud Programming Language by Andija SiskoTrivadis TechEvent 2016 Go - The Cloud Programming Language by Andija Sisko
Trivadis TechEvent 2016 Go - The Cloud Programming Language by Andija Sisko
Trivadis
 
10 reasons to be excited about go
10 reasons to be excited about go10 reasons to be excited about go
10 reasons to be excited about go
Dvir Volk
 
Programming with Python - Adv.
Programming with Python - Adv.Programming with Python - Adv.
Programming with Python - Adv.
Mosky Liu
 
Learn python – for beginners
Learn python – for beginnersLearn python – for beginners
Learn python – for beginners
RajKumar Rampelli
 
Golang and Eco-System Introduction / Overview
Golang and Eco-System Introduction / OverviewGolang and Eco-System Introduction / Overview
Golang and Eco-System Introduction / Overview
Markus Schneider
 
OpenGurukul : Language : Python
OpenGurukul : Language : PythonOpenGurukul : Language : Python
OpenGurukul : Language : Python
Open Gurukul
 
OpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ ProgrammingOpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ Programming
Open Gurukul
 
EuroPython 2016 - Do I Need To Switch To Golang
EuroPython 2016 - Do I Need To Switch To GolangEuroPython 2016 - Do I Need To Switch To Golang
EuroPython 2016 - Do I Need To Switch To Golang
Max Tepkeev
 
Hands on Session on Python
Hands on Session on PythonHands on Session on Python
Hands on Session on Python
Sumit Raj
 
Introduction to Clime
Introduction to ClimeIntroduction to Clime
Introduction to Clime
Mosky Liu
 
Go programming introduction
Go programming introductionGo programming introduction
Go programming introduction
Ginto Joseph
 

Similar to Go Language Hands-on Workshop Material (20)

made it easy: python quick reference for beginners
made it easy: python quick reference for beginnersmade it easy: python quick reference for beginners
made it easy: python quick reference for beginners
SumanMadan4
 
pythonQuick.pdf
pythonQuick.pdfpythonQuick.pdf
pythonQuick.pdf
PhanMinhLinhAnxM0190
 
python notes.pdf
python notes.pdfpython notes.pdf
python notes.pdf
RohitSindhu10
 
python 34💭.pdf
python 34💭.pdfpython 34💭.pdf
python 34💭.pdf
AkashdeepBhattacharj1
 
Python programing
Python programingPython programing
Python programing
hamzagame
 
Bikalpa_Thapa_Python_Programming_(Basics).pptx
Bikalpa_Thapa_Python_Programming_(Basics).pptxBikalpa_Thapa_Python_Programming_(Basics).pptx
Bikalpa_Thapa_Python_Programming_(Basics).pptx
Bikalpa Thapa
 
Javascript
JavascriptJavascript
Javascript
Gita Kriz
 
Go 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX GoGo 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX Go
Rodolfo Carvalho
 
C language (1).pptxC language (1C language (1).pptx).pptx
C language (1).pptxC language (1C language (1).pptx).pptxC language (1).pptxC language (1C language (1).pptx).pptx
C language (1).pptxC language (1C language (1).pptx).pptx
RutviBaraiya
 
Elements of programming
Elements of programmingElements of programming
Elements of programming
baabtra.com - No. 1 supplier of quality freshers
 
Chapter 2-Python and control flow statement.pptx
Chapter 2-Python and control flow statement.pptxChapter 2-Python and control flow statement.pptx
Chapter 2-Python and control flow statement.pptx
atharvdeshpande20
 
Python
PythonPython
Python
MeHak Gulati
 
C lecture 4 nested loops and jumping statements slideshare
C lecture 4 nested loops and jumping statements slideshareC lecture 4 nested loops and jumping statements slideshare
C lecture 4 nested loops and jumping statements slideshare
Gagan Deep
 
golang_getting_started.pptx
golang_getting_started.pptxgolang_getting_started.pptx
golang_getting_started.pptx
Guy Komari
 
Android code convention
Android code conventionAndroid code convention
Android code convention
Siddiq Abu Bakkar
 
Switch case and looping
Switch case and loopingSwitch case and looping
Switch case and looping
ChaAstillas
 
C Programming Unit-2
C Programming Unit-2C Programming Unit-2
C Programming Unit-2
Vikram Nandini
 
PHP slides
PHP slidesPHP slides
PHP slides
Farzad Wadia
 
C++ programming
C++ programmingC++ programming
C++ programming
viancagerone
 
C++ programming
C++ programmingC++ programming
C++ programming
viancagerone
 
made it easy: python quick reference for beginners
made it easy: python quick reference for beginnersmade it easy: python quick reference for beginners
made it easy: python quick reference for beginners
SumanMadan4
 
Python programing
Python programingPython programing
Python programing
hamzagame
 
Bikalpa_Thapa_Python_Programming_(Basics).pptx
Bikalpa_Thapa_Python_Programming_(Basics).pptxBikalpa_Thapa_Python_Programming_(Basics).pptx
Bikalpa_Thapa_Python_Programming_(Basics).pptx
Bikalpa Thapa
 
Go 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX GoGo 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX Go
Rodolfo Carvalho
 
C language (1).pptxC language (1C language (1).pptx).pptx
C language (1).pptxC language (1C language (1).pptx).pptxC language (1).pptxC language (1C language (1).pptx).pptx
C language (1).pptxC language (1C language (1).pptx).pptx
RutviBaraiya
 
Chapter 2-Python and control flow statement.pptx
Chapter 2-Python and control flow statement.pptxChapter 2-Python and control flow statement.pptx
Chapter 2-Python and control flow statement.pptx
atharvdeshpande20
 
C lecture 4 nested loops and jumping statements slideshare
C lecture 4 nested loops and jumping statements slideshareC lecture 4 nested loops and jumping statements slideshare
C lecture 4 nested loops and jumping statements slideshare
Gagan Deep
 
golang_getting_started.pptx
golang_getting_started.pptxgolang_getting_started.pptx
golang_getting_started.pptx
Guy Komari
 
Switch case and looping
Switch case and loopingSwitch case and looping
Switch case and looping
ChaAstillas
 
Ad

More from Romin Irani (16)

Google Cloud Platform Update - NEXT 2017
Google Cloud Platform Update - NEXT 2017Google Cloud Platform Update - NEXT 2017
Google Cloud Platform Update - NEXT 2017
Romin Irani
 
Introduction to Google Cloud Machine Learning APIs
Introduction to Google Cloud Machine Learning APIsIntroduction to Google Cloud Machine Learning APIs
Introduction to Google Cloud Machine Learning APIs
Romin Irani
 
The Journey to conversational interfaces
The Journey to conversational interfacesThe Journey to conversational interfaces
The Journey to conversational interfaces
Romin Irani
 
Blogging Tips - A guide to why you should blog
Blogging Tips - A guide to why you should blogBlogging Tips - A guide to why you should blog
Blogging Tips - A guide to why you should blog
Romin Irani
 
How to Contribute to your Project
How to Contribute to your ProjectHow to Contribute to your Project
How to Contribute to your Project
Romin Irani
 
Google Cloud Platform Updates
Google Cloud Platform UpdatesGoogle Cloud Platform Updates
Google Cloud Platform Updates
Romin Irani
 
Internet of Things Overview
Internet of Things OverviewInternet of Things Overview
Internet of Things Overview
Romin Irani
 
Gradle and Android Studio : Best of Friends
Gradle and Android Studio : Best of FriendsGradle and Android Studio : Best of Friends
Gradle and Android Studio : Best of Friends
Romin Irani
 
Powering your Apps via Google Cloud Platform
Powering your Apps via Google Cloud PlatformPowering your Apps via Google Cloud Platform
Powering your Apps via Google Cloud Platform
Romin Irani
 
How to get business ready for Wearables: GDayX Mumbai 2014
How to get business ready for Wearables: GDayX Mumbai 2014How to get business ready for Wearables: GDayX Mumbai 2014
How to get business ready for Wearables: GDayX Mumbai 2014
Romin Irani
 
Development Workshop on ET1, Android and Motorola RhoElements
Development Workshop on ET1, Android and Motorola RhoElementsDevelopment Workshop on ET1, Android and Motorola RhoElements
Development Workshop on ET1, Android and Motorola RhoElements
Romin Irani
 
Talk on Future of Enterprise Mobile App Development
Talk on Future of Enterprise Mobile App DevelopmentTalk on Future of Enterprise Mobile App Development
Talk on Future of Enterprise Mobile App Development
Romin Irani
 
Android developer webinar-march-2012-mindstormsoftware
Android developer webinar-march-2012-mindstormsoftwareAndroid developer webinar-march-2012-mindstormsoftware
Android developer webinar-march-2012-mindstormsoftware
Romin Irani
 
HTML5 Webinar - Mind Storm Software
HTML5 Webinar - Mind Storm SoftwareHTML5 Webinar - Mind Storm Software
HTML5 Webinar - Mind Storm Software
Romin Irani
 
Smart Computing : Cloud + Mobile + Social
Smart Computing : Cloud + Mobile + SocialSmart Computing : Cloud + Mobile + Social
Smart Computing : Cloud + Mobile + Social
Romin Irani
 
Thadomal IEEE-HTML5-Workshop
Thadomal IEEE-HTML5-WorkshopThadomal IEEE-HTML5-Workshop
Thadomal IEEE-HTML5-Workshop
Romin Irani
 
Google Cloud Platform Update - NEXT 2017
Google Cloud Platform Update - NEXT 2017Google Cloud Platform Update - NEXT 2017
Google Cloud Platform Update - NEXT 2017
Romin Irani
 
Introduction to Google Cloud Machine Learning APIs
Introduction to Google Cloud Machine Learning APIsIntroduction to Google Cloud Machine Learning APIs
Introduction to Google Cloud Machine Learning APIs
Romin Irani
 
The Journey to conversational interfaces
The Journey to conversational interfacesThe Journey to conversational interfaces
The Journey to conversational interfaces
Romin Irani
 
Blogging Tips - A guide to why you should blog
Blogging Tips - A guide to why you should blogBlogging Tips - A guide to why you should blog
Blogging Tips - A guide to why you should blog
Romin Irani
 
How to Contribute to your Project
How to Contribute to your ProjectHow to Contribute to your Project
How to Contribute to your Project
Romin Irani
 
Google Cloud Platform Updates
Google Cloud Platform UpdatesGoogle Cloud Platform Updates
Google Cloud Platform Updates
Romin Irani
 
Internet of Things Overview
Internet of Things OverviewInternet of Things Overview
Internet of Things Overview
Romin Irani
 
Gradle and Android Studio : Best of Friends
Gradle and Android Studio : Best of FriendsGradle and Android Studio : Best of Friends
Gradle and Android Studio : Best of Friends
Romin Irani
 
Powering your Apps via Google Cloud Platform
Powering your Apps via Google Cloud PlatformPowering your Apps via Google Cloud Platform
Powering your Apps via Google Cloud Platform
Romin Irani
 
How to get business ready for Wearables: GDayX Mumbai 2014
How to get business ready for Wearables: GDayX Mumbai 2014How to get business ready for Wearables: GDayX Mumbai 2014
How to get business ready for Wearables: GDayX Mumbai 2014
Romin Irani
 
Development Workshop on ET1, Android and Motorola RhoElements
Development Workshop on ET1, Android and Motorola RhoElementsDevelopment Workshop on ET1, Android and Motorola RhoElements
Development Workshop on ET1, Android and Motorola RhoElements
Romin Irani
 
Talk on Future of Enterprise Mobile App Development
Talk on Future of Enterprise Mobile App DevelopmentTalk on Future of Enterprise Mobile App Development
Talk on Future of Enterprise Mobile App Development
Romin Irani
 
Android developer webinar-march-2012-mindstormsoftware
Android developer webinar-march-2012-mindstormsoftwareAndroid developer webinar-march-2012-mindstormsoftware
Android developer webinar-march-2012-mindstormsoftware
Romin Irani
 
HTML5 Webinar - Mind Storm Software
HTML5 Webinar - Mind Storm SoftwareHTML5 Webinar - Mind Storm Software
HTML5 Webinar - Mind Storm Software
Romin Irani
 
Smart Computing : Cloud + Mobile + Social
Smart Computing : Cloud + Mobile + SocialSmart Computing : Cloud + Mobile + Social
Smart Computing : Cloud + Mobile + Social
Romin Irani
 
Thadomal IEEE-HTML5-Workshop
Thadomal IEEE-HTML5-WorkshopThadomal IEEE-HTML5-Workshop
Thadomal IEEE-HTML5-Workshop
Romin Irani
 
Ad

Recently uploaded (20)

Solidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license codeSolidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license code
aneelaramzan63
 
The Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdfThe Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdf
drewplanas10
 
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Andre Hora
 
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage DashboardsAdobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
BradBedford3
 
Meet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Meet the Agents: How AI Is Learning to Think, Plan, and CollaborateMeet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Meet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Maxim Salnikov
 
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
F-Secure Freedome VPN 2025 Crack Plus Activation  New VersionF-Secure Freedome VPN 2025 Crack Plus Activation  New Version
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
saimabibi60507
 
PDF Reader Pro Crack Latest Version FREE Download 2025
PDF Reader Pro Crack Latest Version FREE Download 2025PDF Reader Pro Crack Latest Version FREE Download 2025
PDF Reader Pro Crack Latest Version FREE Download 2025
mu394968
 
Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)
Allon Mureinik
 
Expand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchangeExpand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchange
Fexle Services Pvt. Ltd.
 
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Eric D. Schabell
 
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
Andre Hora
 
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AIScaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
danshalev
 
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Lionel Briand
 
How can one start with crypto wallet development.pptx
How can one start with crypto wallet development.pptxHow can one start with crypto wallet development.pptx
How can one start with crypto wallet development.pptx
laravinson24
 
Download Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With LatestDownload Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With Latest
tahirabibi60507
 
Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]
saniaaftab72555
 
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdfMicrosoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
TechSoup
 
FL Studio Producer Edition Crack 2025 Full Version
FL Studio Producer Edition Crack 2025 Full VersionFL Studio Producer Edition Crack 2025 Full Version
FL Studio Producer Edition Crack 2025 Full Version
tahirabibi60507
 
Douwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License codeDouwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License code
aneelaramzan63
 
Designing AI-Powered APIs on Azure: Best Practices& Considerations
Designing AI-Powered APIs on Azure: Best Practices& ConsiderationsDesigning AI-Powered APIs on Azure: Best Practices& Considerations
Designing AI-Powered APIs on Azure: Best Practices& Considerations
Dinusha Kumarasiri
 
Solidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license codeSolidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license code
aneelaramzan63
 
The Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdfThe Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdf
drewplanas10
 
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Andre Hora
 
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage DashboardsAdobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
BradBedford3
 
Meet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Meet the Agents: How AI Is Learning to Think, Plan, and CollaborateMeet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Meet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Maxim Salnikov
 
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
F-Secure Freedome VPN 2025 Crack Plus Activation  New VersionF-Secure Freedome VPN 2025 Crack Plus Activation  New Version
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
saimabibi60507
 
PDF Reader Pro Crack Latest Version FREE Download 2025
PDF Reader Pro Crack Latest Version FREE Download 2025PDF Reader Pro Crack Latest Version FREE Download 2025
PDF Reader Pro Crack Latest Version FREE Download 2025
mu394968
 
Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)
Allon Mureinik
 
Expand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchangeExpand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchange
Fexle Services Pvt. Ltd.
 
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Eric D. Schabell
 
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
Andre Hora
 
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AIScaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
danshalev
 
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Lionel Briand
 
How can one start with crypto wallet development.pptx
How can one start with crypto wallet development.pptxHow can one start with crypto wallet development.pptx
How can one start with crypto wallet development.pptx
laravinson24
 
Download Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With LatestDownload Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With Latest
tahirabibi60507
 
Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]
saniaaftab72555
 
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdfMicrosoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
TechSoup
 
FL Studio Producer Edition Crack 2025 Full Version
FL Studio Producer Edition Crack 2025 Full VersionFL Studio Producer Edition Crack 2025 Full Version
FL Studio Producer Edition Crack 2025 Full Version
tahirabibi60507
 
Douwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License codeDouwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License code
aneelaramzan63
 
Designing AI-Powered APIs on Azure: Best Practices& Considerations
Designing AI-Powered APIs on Azure: Best Practices& ConsiderationsDesigning AI-Powered APIs on Azure: Best Practices& Considerations
Designing AI-Powered APIs on Azure: Best Practices& Considerations
Dinusha Kumarasiri
 

Go Language Hands-on Workshop Material

  • 1. 1 Go Language Romin Irani | Jan 31 2015 | @iRomin | [email protected]
  • 2. Objectives  What is the Go Language all about?  Whirlwind Tour of the Language  See lots of code samples  Hopefully … make you code a little bit too in this session  Get you interested enough to learn more about Go! 2 Any Prerequisites?
  • 4. Why use Go?  Modern  Popular  Simple  Fun  Do More With Less 4
  • 5. Go Language History  Started in 2007 @ Google  Initial Release in 2009  Rob Pike, Robert Griesemer, Ken Thompson  Designed to overcome issues with using Java, Python and other languages across large code base  Systems Language  General Purpose Language  Current @ 1.5  Version 1.6 to be released in Feb 2016 5
  • 6. Go Features  Similar to C Language in Syntax  Case sensitive  Only 25 keywords  Cross Platform Binaries  Compiled Language  Statically Typed  Solid and comprehensive Standard Packages  Object Oriented Features  Composition over Inheritance  Open Source 6
  • 7. Popular Projects  Popular with Infrastructure Software Companies  Popular Projects  Docker  CoreOS: etcd, rkt  Kubernetes  InfluxDB, RethinkDB  Hugo  Consule  And more  Great choice for a modern, general purpose language 7
  • 9. Go Playground  Go Playground : http://play.golang.or g  Excellent way to get familiar with syntax  Run Go code in the cloud  Save and Share Go Snippets  Some restrictions 9
  • 10. First Go Project  We will be creating a new Project  Let us call it helloworld  Create this project folder in the GOPATH root i.e. $GOPATHhelloworld  Open Atom Editor. Add the $GOPATHhelloworld Project Folder  Create a new file named hello-world.go 10
  • 11. Hello World in Go 11
  • 12. Running our Application  go run <filename>  go run hello-world.go 12
  • 13. Built-in Types 13  bool  string  int int8 int16 int32 int64  uint uint8 uint16 uint32 uint64 uintptr  byte // alias for uint8  rune // alias for int32 // represents a Unicode code point  float32 float64 complex64 complex128
  • 14. Variable Declaration  Use the var keyword  Format var <variablename> <type> var <variablename> <type> = <initialvalue>  Examples: var phoneModel string = “Samsung S5” var osName string = “Android” var price float32 = 40000.0 14
  • 15. Variable Declaration  Use the block declaration to combine multiple variables var ( phoneModel string = “Samsung S5” osName string = “Android” price float32 = 40000.0 ) 15
  • 16. Variable Declaration  Declare multiple variables of the same type as follows: var firstName, lastName string = “A”, “B” var i,j int, k string =10,20,”Hello”  If initializer is present, the type can be omitted: var i,j = 10,20 16
  • 17. Short Variable Declaration  Use the := short assignment statement instead of var  The type is implicit i.e. determined by Go  Available only inside a function and not at package level function main() { price := 20.50 firstName := “Gopher” } 17
  • 18. Constants 18  Declared with the const keyword  They can be character, string, boolean or numeric  The scope depends on where they are defined const tax_rate = 10.5 const city = “Mumbai”
  • 19. Go : Zero values 19  Every type has a Zero value Zero Value Type 0 Numeric false Boolean “” String nil Pointer, channel, struct, func, interface, map, Slice
  • 20. Go : Arithmetic Operators 20 Operator For? + Addition - Subtraction * Multiplication / Division % Remainder
  • 21. Go : Logical Operators 21 Operator For? && Boolean AND || Boolean OR ! NOT == Test equality
  • 22. Reference Types 22  Go also has the following Reference Types  Arrays  Maps  Slices  Structs  Channels  We will look at them later
  • 23. Hands On Exercise #1 & #2 23 Hello World: http://play.golang.org/p/achXqgsH1v Variables, Constants: http://play.golang.org/p/dQuYzSgR0P
  • 24. What are functions?  Functions are the building blocks of Go programs  An independent section of code  Also known as procedure or subroutine  Can take input parameters  Can return single or multiple return values  Variable number of arguments  Functions are first class citizens in Go. They can be passed around as any other value.  Anonymous Functions 24
  • 25. Writing a function  You have already seen the main() function in action 25
  • 26. Writing a function  Define your function by specifying the following: func funcname() { }  This is the simplest way to define a function.  It does not take any input parameters  It does not return any values  E.g. func sayHello() { fmt.Println(“Hello”) } 26
  • 27. Function with input parameters  Define your function by specifying the following: func funcname(param1 type, param2 type) { }  This function takes two input parameters  It does not return any values  E.g. func sayHello(firstName string, lastName string, age int) { fmt.Println(“Hello”,firstName,lastName,”You are”,age,”years old”) } 27
  • 28. Function with input parameters  If multiple parameters are of same type, you can use a short-hand way of declaring: func funcname(param1,param2 type1, param3 type2) { }  f1(num1,num2 int, name string)  f2(num1 int, firstname, lastname string) 28
  • 29. Function with return values  A function can return a value : single or multiple func funcname(param1,param2 type1, param3 type2) (return value types) { }  f1(num1 int, num2 int) (int) { return 0}  f2(num1 int, firstname, lastname string) (int, string) { return 1, “Hello”}  f3(num1 int, num2 int) (int, bool) { return false}  f4(num1 int, num2 int) (int, error) { return 10, nil //return -1, errors.New(“Some error”) } 29
  • 30. Variadic functions  The last input parameter can contain multiple or variable number of arguments  They have to be of the same type func funcname(param1 type1, …string) { } E.g. func addNumbers(numbers …int) (int) { } Invoking it: addNumbers(1,2,3,4,5) addNumbers(1,2) addNumbers(1,2,3,4,5,6,7,8,9,10) 30
  • 32. for construct  The only looping construct available in Go  3 variants  Single condition  Classical For Loop : Initial Value, Final Value, Increment  Forever Loop 32
  • 33. for : Single Condition  for <condition> { }  Repeatedly executes the block while the condition is true Example: for i < 3 { fmt.Println(i) i++ } 33
  • 34. for : Classical Loop for i := 1; i<=10; i++ { fmt.Println(i) }  i:=1 , both declares, initializes the variable i 34
  • 35. for : forever loop for { //do something //if some condition met , then use break }  Similar to while true { … } in other languages  Break out of the loop via the break or return statement 35
  • 36. Sample Code  Go Playground: http://play.golang.org/p/Z7bKxJ-ljK 36
  • 37. if statement  if statement is a condition followed by a block  The block is executed only if the condition evaluates to true if <condition> { //Some statements } if (sum > 100) { … } 37
  • 38. if – else statement if <condition> { //block 1 } else { //block 2 } a:=1 b:=2 if a > b { fmt.Println(“a is greater than b”) } else { fmt.Println(“a is less than or equal to b”) } 38
  • 39. If-else-if statement if <condition 1> { //block 1 } else if <condition 2> { //block 2 } else if <condition 3> { } else { } 39
  • 40. switch statement 40  switch statement can help in evaluating multiple conditions  The switch keyword is followed by an expression and then multiple case statements, out of which one will be executed  The case data types could be int, float, string, bool, etc. or even a complex expression / function call  Unlike other languages, there is no need for the break statement after each case statement.  A default case statement can be put too in case none of the case conditions are met.
  • 41. switch statement switch i { case 0: fmt.Println("Zero") case 1: fmt.Println("One") case 2: fmt.Println("Two") case 3: fmt.Println("Three") case 4: fmt.Println("Four") case 5: fmt.Println("Five") default: fmt.Println("Unknown Number") } 41
  • 42. switch statement 42  Notice that there was no break statement between the case statements  If you want the code to fallthrough like it is in under languages, use fallthrough
  • 43. switch statement 43  Use commas to separate multiple expressions in same case statement. switch i { case 1,3,5,7,9: fmt.Println(“Odd") case 2,4,6,8,10: fmt.Println(“Even") default: fmt.Println("Unknown Number") }
  • 44. switch – without expression 44  Eliminate the expression in switch statement. This way, it can evaluate the case expression switch { case i < 10: fmt.Println(“Less than 10") case i>=10 && i <=100 : fmt.Println(“Between 10 and 100") case somefunc(i) > 200 : fmt.Println(“some statement”) default: fmt.Println("Unknown Number") }
  • 45. Sample Code  Go Playground:  if / if - else: http://play.golang.org/p/bA0qVEx_eP  switch :  http://play.golang.org/p/wjwTpPLujg  http://play.golang.org/p/lQQIiLzC1G  http://play.golang.org/p/5rj5Y1hVPR 45
  • 47. Arrays in Go  Fixed length data type for holding elements of same type  Array can be of any types like int, string, struct, pointers, etc  Individual element of Array can be accessed using integer index, using []. For e.g. num[0]  Array index is 0 bound that if Array size is 5, index ranges from 0 to 4 47
  • 48. Declaring / Initializing Arrays  var iArr = [5]int{}  Creates an Array of length 5  Each element of Array initialized to zero value i.e. 0  iArr := [5]int {0, 1, 2, 3, 4} Declare and initialize Array iArr of length 5, and with values 0, 1, 2, 3, 4  iArr := [5]int {2: 20, 4: 50}: Declare and initialize Array iArr of length 5, and will set value at index 2 and 4 to 20 and 50 respectively 48
  • 49. Accessing Array elements  iArr[2], will access element at index 2 of Array iArr  iArr[3] = 10, will set 10 as value at index 3  If index is more than length of Array, then an error is thrown. For e.g. iArr[5] for an integer Array of 5 elements will thrown the follow error: “invalid Array index 5 (out of bounds for 5-element Array)” 49
  • 50. Iterating through Array  Use the for or range statement var numbers = [5]int{1,2,3,4,5} for i:=0;i<5;i++ { //numbers[i] } Use built-in len function for length of Array. For e.g. for i:=0;i<len(numbers);i++ { //numbers[i] } 50
  • 51. Iterating through Array  for + range statement allows you to iterate over a collection.  It provides both index and value of each item var numbers = [5]int{1,2,3,4,5} for index,value := range numbers { fmt.Println(index,value) } Output: 0,1 1,2 2,3 3,4 4,5 51
  • 52. Iterating through Array  You can ignore any of the index or value , if not interested var numbers = [5]int{1,2,3,4,5} for _,value := range numbers { fmt.Println(value) } var numbers = [5]int{1,2,3,4,5} for index, _ := range numbers { fmt.Println(index) } Question : Why do you need to ignore any of the return values that you are not interested in? 52
  • 53. Array Sample code 53 1. Multiple Array examples http://play.golang.org/p/p-eV7eZXYp 2. Pass by Value to function 3. Using for and range to iterate over Array http://play.golang.org/p/nN1Q3R0Z1X 4. A first look at Slices: http://play.golang.org/p/WarnTGxDaE
  • 54. Arrays : Practical Considerations  Fixed in Length  Arrays are passed by value to function  If the Array data is large in size ( or multi- dimensional), impact memory and performance  Go has a solution to addressing this that we shall see in the next section : Slices 54
  • 55. Slices - Overview  Slice data type is similar to an Array  Just like an Array, a Slice too holds elements of same type  It does not have a fixed length  A Slice allows for dynamic expansion and shrinking of the Array  It is an abstraction built on top of an Array type and shares same memory as that of underlying Array 55
  • 56. Declaring / Initializing  Use make function for creating a Slice make([]T, length, capacity)  T is the type of element to hold  length, of Slice to be created. It is mandatory to specify length  capacity, of Slice to be created. It is optional to specify capacity. In case if not specified , capacity is assumed to be same as length 56
  • 57. Declaring / Initializing  Slice := make([]int, 5, 10) This will create Slice of type int, of length 5 and capacity 10.  Slice := make([]int, 5) This will create Slice of type int, of length 5 and capacity 5. 57
  • 58. Declaring / Initializing  Slice is used in same way as Array. Slice[0] = 1 Slice[1] = 2 Setting values at index 0 and 1 into Slice  Use function len to find length of Slice  Use function cap to find capacity of Slice 58
  • 59. append function  It is always recommended to use append method while adding value(s) to Slice  Function append, internally checks if value to be added in more than the length, it will create new Array using capacity and add new value.  Call to append always returns new Slice 59
  • 60. Slicing Arrays  So far we created Slice using make function, which also creates underlying Array for Slice  But we can also create Slice on top of Array Let us assume Array i := [5] int {1, 2, 3, 4, 5}  Slice := i[1:3] This will create Slice over Array i, using values starting from index 1 to 3 i.e. 2, 3, 4.  Slice := i[:] This will create Slice covering entire Array i.e. from index 0 to 4. 60
  • 61. Declaring / Initializing  Slice := [] int {1, 2, 3, 4, 5} Creating Slice in same way as Array. But here we don’t specify length in the preceding square brackets  Empty Slices:  Slice := []int {}  Slice := make ([]int, 0)  Creating new Slice from Slice  Slice2 := Slice[1: 3] 61
  • 62. Slice Representation 62 Pointer (0) 1 (1) 2 (2) 3 (3) 4 (4) 5 Slice := [] int {1, 2, 3, 4, 5} Pointer new_Slice := Slice[2 : 4]
  • 63. Key points while using Slices  Slice is a reference to an Array  All the Slices on an Array shares same memory as that of Array  Can create more than one Slice on same underlying Array  Any changes made to one Slice will be reflected in other Slices and in Array too  Useful to use a slice instead of entire Array in case of large amount of data 63
  • 64. Iterating over Slices  Use the range keyword numbers := []int{100, 200, 300, 400, 500} for index, value := range numbers { fmt.Println(index, value) }  Go Playground http://play.golang.org/p/P_nSXzxAC1 64
  • 65. Examples  Slice from make function http://play.golang.org/p/sGQ2WOT1S3  Slice from Literal http://play.golang.org/p/R60h2f2xt9  append, len and capacity functions http://play.golang.org/p/gUPJNCelX0  Slices are passed by value to functions http://play.golang.org/p/nluakS7P-s  Multiple Slices work over the same array http://play.golang.org/p/BsHTCliECU  Iterating over Slices http://play.golang.org/p/6Ax7L6Ud7E 65
  • 66. Map  Only key/value paired collection in Go  Map is an unordered collection i.e. order in which key/value returned is not always the same  Map, uses a hash table for storing key/value 66
  • 67. Declaring/Initializing  Use function make for creating Map make(map[key type]value type) In make function, use keyword map, specify the type to be used as key in square brackets and type to be used as value outside square bracket m := make(map[int]string) This will create a Map, with key as int and value as string 67
  • 68. Declaring/Initializing  We can also create without using make function m := map[int]string{}  It is also possible to declare and initialize map in one statement m := map[int]string { 1: “One”, 2: “Two”, 3: “Three”, } 68
  • 69. Using Map  Write to map m[4] = “Four” This will add, key 4, and assign “Four” as it is value  Read from map s := m[2] Will return value for key 2 i.e. “Two”.  In case if key is not present in map, it will return zero value for type of value. In our case if we use m[100] and since key 100 is not present in map, empty string will be returned as for string, empty string is zero value 69
  • 70.  Function len, can be used to determine length/size of the map  Function delete, to be used to deleting key/value from map delete(m, 1) Will delete key/value pair whose key is 1 from map m. If m is nil or key is not present in map, delete will be no operation 70 Using Map
  • 71. Using Map  i, ok := m[1] Here 2 values will be returned, 1st the value for key and 2nd boolean to indicate if key/value exists  i := m[100] Here only value for the key will be returned  _, ok := m[100] This can be used to check if key/value exists. We have used blank Identifier (Underscore) as 1st value to skip it 71
  • 72. Iterating a Map m := map[int]string{ 1: “One”, 2 : “Two”, 3: “Three”, } We can iterate over map using range as shown below for k, v : range m { fmt.Println(“Key :”, k, “ Value :”, v) } Two values are returned, 1st is key and 2nd is value. 72
  • 73. Examples  Creating a Map http://play.golang.org/p/8P-lR6XXe0 Accessing Map (Example 1) http://play.golang.org/p/nSh2EpFsGa  Accessing Map (Example 2) http://play.golang.org/p/VQ0EZJoCWt  Function http://play.golang.org/p/YNtjqHYCbd 73
  • 75. Structs  Struct is user defined data type  Struct, as the name says is a structure used for logical grouping of fields/property  If you are familiar with OO language Java, you can co-relate it with class  A Struct, like most other data types when passed as parameter to function is passed by value 75
  • 76. Declaring/Initializing  Following is the template used for declaring a struct type <name> struct { } keyword type is used to define a new type followed with name of the struct, followed by keyword struct to indicate that type is a struct  Example type User struct { FirstName string LastName string Age int } 76
  • 77. Declaring/Initializing  Just like any other data type, A Struct too can be declared and initialized in two steps var u User This will declare variable of u of type struct User and initialize it to zerovalue.  We can do declaration and initialization in one statement as shown below: u := new(User) Using new will allocate memory and return pointer. 77
  • 78. Declaring/Initializing  We can pass values for each of the property to be initialized at the time of creating an instance of struct. u := User{“Fn”, “Ln”, 50} Here we have passed value as Fn, Ln and 50 which will be set to FirstName, LastName and Age respectively.  We can also specify property name explicitly in case if we don’t wish to initialize all the properties or if we don’t want to follow sequential approach u := User{Age: 50, FirstName: “Fn”} 78
  • 79. Accessing  We can access individual fields as follows: u := User{Age: 50, FirstName: “Fn”} Here we have not initialized LastName while creating instance of User. Lets do it now: u.LastName = “Ln”  Use Println, for printing a Struct including all it fields fmt.Println(u) This will print: {Fn Ln 50} 79
  • 80. Nested Struct type Address struct { Building, Area, City, State, Country string } type User struct{ … Address Address } u := User{Age: 50, FirstName: "Fn", LastName:"Ln"} u.Address = Address{"building", "area", "city", "state", "INDIA"} fmt.Println(u) Output: {Fn Ln 50 {building area city state INDIA}} 80
  • 81. Struct : Receiver Methods  Method is a function which is called upon instance. For example: func (u User) isSeniorCitizen() bool{ isSrCitizen := false if (u.Age > 60){ isSrCitizen = true } return isSrCitizen } Note the signature, we are preceding the function name with instance of user. This is called as receiver and function is called as method on User. We can call this method as u := User{Age: 50, FirstName: "Fn", LastName:"Ln"} isSrCitizen := u.isSeniorCitizen() 81
  • 83. Interfaces  Interface is a way to add behaviour  It is GoLang’s way to Polymorphism  Interface is a contract that implementer needs to fulfill  Interface only defines methods with signature without definition. Definition of methods is left up- to implementer  Interface leads to IS-A relationship  You can add behaviour anytime by implementing the Interface method. This is one of the nice features of the language 83
  • 84. Declaring type <name> interface{ …. }  Interface is declared using keyword type followed by name followed by keyword interface  Example type Shape interface { printArea() } Here we have declared interface of type Shape with method printArea, which needs to be implemented by implementer 84
  • 85. Implementation type Square struct { side int } func (s Square) printArea (){ fmt.Println(“Area of Square”, s.side * s.side) } type Rectangle struct { length, breath int } func (r Rectangle ) printArea(){ fmt.Println(“Area of Rectangle”, r.length * r.breath) } 85
  • 86. Implementation func main(){ var s, r Shape s = Square{5} r = Rectangle{5, 4} s.printArea() r.printArea() } Output: Area of Square 25 Area of Rectangle 20 We have created instance of Square and Rectangle and called printArea() method on each of them. 86
  • 87. Composition over Inheritance  Go does not support inheritance  It supports Composition via Type Embedding  The design philosophy is to compose large things from smaller components  Composition over Inheritance helps to keep the components loosely coupled even as changes happen in the system + helps with practical benefits of inheritance 87
  • 88. Composition Example  Composition is Go is done via Embedding the Type  The embedding struct gets the behaviour of the embedded Type  It can also access the struct elements directly  It can override the behaviour of Embedded Type if needed  Though Composition is HAS-A , it is easier to think of via IS-A 88
  • 89. Interfaces + Type Composition  You can define an Interface with its methods  A Type (Struct) can implement it.  You can then embed that type into any struct  The Embedding Struct can override behaviour if needed  You can treat all the instances like IS-A type of that particular Interface 89
  • 90. Hands On Exercise #7 & #8 90 http://play.golang.org/p/toycLtAVxz http://play.golang.org/p/i1Hpf2YA5-
  • 91. Concurrency in Go  What is concurrency?  Concurrency v/s Parallelism  Go routines  Channels  See sample code to see it work 91
  • 93. Threads Anyone?  Usually the execution of things concurrently is done via an OS Thread  On a single core CPU, only one thread can be executing at a single time  Threads are resource hungry and not that lightweight  Go does not use Threads  Instead it uses go routines. Let’s check that. 93
  • 94. go routines  It is a light weight construct  Go manages go routines  Go routines are laid on top of threads  Switching Threads is expensive  Since multiple go routines could be in a thread, switching is less expensive , therefore less scheduling of Threads  Faster startup times  Communicating between go routines is via Channels 94
  • 95. Step 1 : Running Sequentially  Go Playground http://play.golang.org/p/OCHJV_xbI0  This code invokes two functions , one after the other  There is no concurrency here 95
  • 96. Step 2 : Introduce go routines  Go Playground http://play.golang.org/p/VZqsEyZbKG  Simply put the keyword go before the function call  This will invoke the two functions concurrently  Investigate : What happened?  The program just exited  This is because the main routine ended immediately  Suggested Fix : Maybe a timer ? 96
  • 97. Step 3 : Introduce a Timer  Go Playground http://play.golang.org/p/dsno9tkdb0  Introduced the time.Sleep method in both the go routines so that each one of them allows the other to run  Additionally, we have put a longer timer in the main routine so that there is sufficient time for the go routines to complete  Issue : We cannot keep playing with the timer 97
  • 98. Step 4 : Introducing sync.WaitGroup  Go Playground http://play.golang.org/p/vavJveNVer  Use a WaitGroup from sync package  In the main routine, you can specify how many go routines need to finish and one waits for that  Each go routine will indicate to the Wait Group that is done 98
  • 99. Go Channels  Synchronization between go routines is done via Channels  A Channel can be thought of as a pipe that connects the go routines  Communication means “exchange of data”  Channels take care of safely transmitting data between the go routines and takes care of sync operations  Channels  Buffered  Un-buffered (Default) 99
  • 100. Unbuffered Channel  Creation  ch1 := make(chan <datatype>)  Writing to it : ch1 <- somedata  Reading from it : somedata <- ch1 100
  • 101. Unbuffered Channel  Sender go routine will write data to the Channel  Receiver go routine will wait on the Channel  The Sender blocks till the Receiver gets the data  The Receiver blocks till it receives the data  Unbuffered Channel = Combines Communication with Synchronization 101
  • 102. Unbuffered Channel : Example  Go Playground http://play.golang.org/p/T8_4wz0fjw  Main routine (RECEIVER) waits for a message on the channel  go routine (SENDER) – completes it’s task and sends the message on the channel  Try: Comment out the go f1() line and see what happens when you try to run! 102
  • 103. Buffered Channel  Creation  ch1 := make(chan <datatype>, size)  Writing to it : ch1 <- somedata  Reading from it : somedata <- ch1 103
  • 104. Buffered Channel  Sender go routine will write data to the Channel  Receiver go routine will wait on the Channel  The number of data blocks that can be written depend on size  The Sender go routine will not block after writing if the buffer is still available  The Receiver blocks till it receives the data  Buffered Channel = Semaphore to limit throughput 104
  • 105. Buffered Channel : Example  Go Playground: http://play.golang.org/p/ft03nGBshb  Create a channel that accepts a string with a buffer size of 2  Main routine can wait for both go routines to write to that channel  Try : Uncomment the extra fmt.Println(<- messageChannel) line 105
  • 106. Buffered Channel : Example  Go Playground: http://play.golang.org/p/E3YikZ8UEv  Channel that accepts string data type and buffer size of 5  Go routine sends the 5 messages and since it is buffered, it is not blocked till the RECEIVER gets it.  Try : Introduce a timer if you want to sleep in main routine and get the message later. 106
  • 107. Understand Buffered Channels  Go Playground: http://play.golang.org/p/4Cbc7BfE7s  The channel size is 5  Notice how the go routine (SENDER) after publishing 5 messages to the Buffered Channel BLOCKS on the 6th message till the RECEIVER starts reading from the channel 107
  • 108. Go & Web Development  Well suited to power web applications  Sweet spot lies in creating Web APIs that can be consumed by clients  Core packages : net/http and html/template  Web Frameworks:  Martini  Revel  Others 108
  • 109.  Powerful standard library to handle Request / Response pattern  The key component here is http.HTTPHandler , which encapsulates the Request / Response 109 net/http Package
  • 110. Various HTTP Handlers  net/http provides several HTTP Handlers like FileServer, NotFoundHandler, etc.  Example : FileServer can be used for Static File Serving  http.FileServer(root FileSystem)  Using http.ListenAndServe(port,handler) – we can serve a static site  Create the following file http://play.golang.org/p/KyRDyXSpm7 in any server and run the application there. Visit localhost:8080 in your browser. 110
  • 111. net/http Package  We need to typically map multiple URL Paths to their HTTP Handlers  For e.g.  /add -> Handler 1  /edit -> Handler 2  /delete -> Handler 3  ServeMux in net/htttp 111 ServeMux HTTP Router Handler 1 Handler 2 Handler 3 /add /edit /delete Req Res p
  • 112. Sample REST API  Write a REST API for managing Employees  To keep it simple, we will implement single GET method call /employees to get all employees  Go Playground http://play.golang.org/p/ged5yNOekx 112
  • 113. HTTP Networking - Invoking REST API  Use the net/http package  Package http provides HTTP client and server implementations  Get, Head, Post, and PostForm methods to make HTTP (or HTTPS) requests  resp, err := http.Get("http://example.com/")  resp, err := http.Post("http://example.com/upload", "image/jpeg", &buf)  resp, err := http.PostForm("http://example.com/form", url.Values{"key": {"Value"}, "id": {"123"}}) 113
  • 114. Sample Code  USD to INR Currency Rate  Invokes a Currency REST API that returns JSON Data  http://apilayer.net/api/live?access_key=API_KEY& currencies=INR&format=1  Go Playground  Step 1 : Retrieve JSON Data : http://play.golang.org/p/H5-JX-1VEP  Step 2 : Parse the JSON Data : http://play.golang.org/p/Fp8S78V5UC 114
  • 115. Several Other things …  Unit Testing  Go Tools  Go Doc  Take a look at : https://github.com/avelino/awesome-go 115
  • 116. Naming conventions  Create the test file with name ending in _test.go  Inside the test file, each test is written in the following form: func TestXyz(t *testing.T)  go build ignores the files ending in _test.go  go test will take all the files ending in _test.go  go help test 116
  • 117. Go Documentation  Go provides godoc tool for generating documentation from source files  You can use it to get information on packages too  See all documentation godoc -http=:4000  See specific documentation on a package godoc math  See specific documentation on a package + function godoc strconv Atoi 117
  • 118.  Q & A  Website : http://www.rominirani.com  Email : [email protected]  Twitter : @iRomin 118 Thank You