6. Sample func+on
package main
import “fmt”
func split(sum int) (x, y int) {
x = sum * 4 / 9
y = sum - x
return
}
func main() {
var x, y, z int
fmt.Println(x,y,z)
fmt.Println(split(17))
}
9. Object Oriented Go
• No classes, no inheritance
• go has duck typing
• structs are used for custom types, aggrega+on
• Interfaces, abstract type has methods
• Any custom type having same methods as
interface follows that (and/or other) interface
• Interface{}, empty interface is like void in C or
Object in Java
10. Interface
type Printer interface {
Print()
}
type MyFloat float64
func (f MyFloat) Print() {
fmt.Println(f);
}
func main() {
var a Printer
f := MyFloat(5.5)
a = f
}
11. Features 1/2
• Garbage collec+on
• Concurrency
• Packages
– fmt, net, os, +me, math, zlib
– h-p://golang.org/pkg/ has the exhaus+ve list
• Types
– bool, int, int8, int16, int32, int64, uint …, byte, float32,float64,
complex64, complex128
– const
• For loop only
• struct, access fields using dot
• Pointer but no pointer arithme+c
12. Features 2/2
• Slices
– s := []int{2, 3, 5, 7, 11, 13}
– len(s)
• Maps
– var m map[string]string
– m[“index”]
• Func+on values
f1 := func(x, y float64) float64 {
return math.Sqrt(x*x + y*y)
}
13. Concurrency
• go rou+nes
– Lightweight thread like rou+ne (may be one or more
thread)
• Channels and Buffered Channel
– Useful for sync between go rou+nes
– Send and receive to channel is blocking ( no sync needed)
• Range and close
– Range used itera+ng over channel
– Close used by sender aier sending all values
• Select
– Lets gorou+ne waits on mul+ple communica+on
opera+ons
14. JSON and Go
type Message struct {
Name string
Body string
Time int64
}
m := Message{"Alice", "Hello", 1290090}
b, err := json.Marshal(m)
-----------
b is now
[]byte(`{"Name":"Alice","Body":"Hello","Time
":1290090}`)
15. Web Server
type Hello struct{}
func (h Hello) ServeHTTP(
w http.ResponseWriter,
r *http.Request) {
fmt.Fprint(w, "Hello TechNext !")
}
func main() {
var h Hello
http.ListenAndServe("localhost:4000", h)
}
16. MongoDB Driver (mgo)
• Mgo Driver can be fetched using
– go get gopkg.in/mgo.v2
– go get gopkg.in/mgo.v2/bson
• Sample code to connect to mongo
session, err := mgo.Dial("localhost”)
collection :=
session.DB(”mydb").C(”mycollection”)
err := collection.Find(bson.M{”Name”:
“XYZ”}).One(&result)
17. Go In Produc+on
• Google is using in produc+on for
– h-p://golang.org
– Vitess system for large-scale SQL installa+ons
– Download server dl.google.com
• It delivers chrome binaries and apt-get packages
• Other companies using Go in produc+on
– InfluxData
– Canonical
– Heroku
– Iron.io
– Apcera
– Docker
– h-p://go-lang.cat-v.org/organiza+ons-using-go