Introduction to Golang
Speak Your Way, February 1, 2017
Yoni Davidson
Sears Israel
From Wikipedia - What is Go
Go (often referred to as golang) is a free and open source[12]
programming language created at Google[13]
in 2007 by Robert Griesemer,
Rob Pike, and Ken Thompson.
[10]
It is a compiled, statically typed language in the tradition of Algol and C, with garbage collection, limited
structural typing,[3]
memory safety features and CSP-style concurrent programming features added.[14]
Hello, world
package main
import "fmt"
func main() {
fmt.Printf("Hello, 世界n");
}
Taken from: https://talks.golang.org/2009/go_talk-20091030.pdf
Who
Robert Griesemer, Ken Thompson, and Rob Pike started the project in late 2007.
By mid 2008 the language was mostly designed and the implementation (compiler,
run-time) starting to work.
Ian Lance Taylor and Russ Cox joined in 2008.
Lots of help from many others (Open source).
Taken from: https://talks.golang.org/2009/go_talk-20091030.pdf
Why
Go fast! Make programming fun again.
There is focus on building client/server systems.
Clusters can be massive.
The rise of multi-core CPUs.
Major system languages were not designed with all these factors in mind.
Taken from: https://talks.golang.org/2009/go_talk-20091030.pdf
Construction speed
Takes too long to build software.
Tools are slow.
Dependencies management is hard.
Machines stopped getting faster (Dramatically).
Taken from: https://talks.golang.org/2009/go_talk-20091030.pdf
Type system
Clunky typing: Taints good idea with bad implementation. Makes programming
harder (think of C's const: well-intentioned but awkward in practice).
Hierarchy is too stringent: Types in large programs do not easily fall into
hierarchies.
Programmers spend too much time deciding tree structure and rearranging
inheritance.
You can be productive or safe, not both.
Taken from: https://talks.golang.org/2009/go_talk-20091030.pdf
Why a new language?
These problems are endemic and linguistic.
New libraries won’t help. (Adding anything is going in the wrong direction.)
Need to start over, thinking about the way programs are written and constructed.
Taken from: https://talks.golang.org/2009/go_talk-20091030.pdf
Goals
The efficiency of a statically-typed compiled language with the ease of
programming of a dynamic language.
Safety: type-safe and memory-safe.
Good support for concurrency and communication.
Efficient, latency-free garbage collection.
High-speed compilation.
Taken from: https://talks.golang.org/2009/go_talk-20091030.pdf
https://xkcd.com/303/
Taken from: https://talks.golang.org/2009/go_talk-20091030.pdf
Example
Where can we find go?
Traditionally in server side infrastructure (High query rate servers, Web crawlers):
Some well known CLI/Server projects.
Where can we find go?
IOT devices:
Mobile:
Go best advantages:
Golang compiles natively to most important architectures (arm, x86).
Development is faster in comparison to C ,C++ Java.
Deployment of code on ServerpcIOT is simple due to the nature of static
compilation.
Context switch between backend and device is simpler if you use go in both.
Concurrency is easily used in go (in comparison to C/C++/java) lets you better
exploit multi core architectures (very common today).
Go best advantages:
No file system dependency (Java , Nodejs, C++ - boost) - Code runs natively.
Large and growing collection of open source code for large range of abilities.
Compiles easily with C.
Internal tools in go
build compile packages and dependencies
clean remove object files
doc show documentation for package or symbol
env print Go environment information
fix run go tool fix on packages
fmt run gofmt on package sources
generate generate Go files by processing source
get download and install packages and dependencies
install compile and install packages and dependencies
list list packages
run compile and run Go program
test test packages
tool run specified go tool
version print Go version
vet run go tool vet on packages
Example simple web server:
package main
import (
"fmt"
"http"
)
func handler(c *http.Conn, r *http.Request) {
fmt.Fprintf(c, "Hello, %s.", r.URL.Path[1:])
}
func main() {
http.ListenAndServe(":8080",
http.HandlerFunc(handler))
}
https://talks.golang.org/2010/ExpressivenessOfGo-2010.pdf
Structs
type Point struct { x, y float }
func (p Point) Abs() float {
return math.Sqrt(p.x*p.x + p.y*p.y)
}
Structs describe (and control) the layout of data.
Methods are not mixed with the data definition.
They are orthogonal to types.
https://talks.golang.org/2010/ExpressivenessOfGo-2010.pdf
Methods
Orthogonality of methods allows any type to have them.
type Vector []float
func (v Vector) Abs() float {
sumOfSquares := 0.0
for i := range v {
sumOfSquares += v[i]*v[i]
}
return math.Sqrt(sumOfSquares)
}
It also allows receivers to be values or pointers:
func (p *Point) Scale(ratio float) {
p.x, p.y = ratio*p.x, ratio*p.y
}
func swap(x, y string) (string, string) { //multiple results
return y, x
}
Interfaces
Interfaces are just sets of methods. work for any type.
type Abser interface {
Abs() float
}
var a Abser
a = Point{3, 4}
print(a.Abs())
a = Vector{1, 2, 3, 4}
print(a.Abs())
Interfaces are satisfied implicitly. Point and Vector do not
declare that they implement Abser, they just do!
Error handling
Functions often return an error value, and calling code should handle errors by testing whether
the error equals nil.
type error interface {
Error() string
}
Error handling - example
type MyError struct {
When time.Time
What string
}
func (e *MyError) Error() string {
return fmt.Sprintf("at %v, %s",
e.When, e.What)
}
func run() error {
return &MyError{
time.Now(),
"it didn't work",
}
}
func main() {
if err := run(); err != nil {
fmt.Println(err)
}
}
Concurrency
Go's approach to concurrency differs from the traditional use of threads and shared memory. Philosophically, it can be summarized:
Don't communicate by sharing memory; share memory by communicating.
Goroutines
A goroutine is a function that is capable of running concurrently with other functions. To create a goroutine we use the keyword
go followed by a function invocation.
Channels
Channels provide a way for two goroutines to communicate with one another and synchronize their execution.
Go concurrency basics
Start a goroutine:
go f()
Channel send (arrow points in direction of flow):
ch <- value
Channel receive:
value = <-ch
Channels are unbuffered by default, which combines
synchronization with communication.
Launching a goroutine
Start a service, return a channel to communicate with it:
package main
func main() {
// create new channel of type int
ch := make(chan int)
// start new anonymous goroutine
go func() {
// send 42 to channel
ch <- 42
}()
// read from channel
<-ch
}
1. package main
2. import "time"
3. func main() {
4. var Ball int
5. table := make(chan int)
6. go player(table)
7. go player(table)
8. table <- Ball
9. time.Sleep(1 * time.Second)
10. <-table
11. }
12. func player(table chan int) {
13. for {
14. ball := <-table
15. ball++
16. time.Sleep(100 * time.Millisecond)
17. table <- ball
18. }
19. }
Closures are just local functions
func Compose(f, g func(x float) float) func(x float) float {
return func(x float) float {
return f(g(x))
}
}
Closures
Closures and concurrency
Query servers in replicated database, return first response.
func Query(conns []Conn, query string) Result {
ch := make(chan Result, 1) // buffer of 1 item
for _, conn := range conns {
go func(c Conn) {
_ = ch <- c.DoQuery(query)
}(conn)
}
return <-ch
}
This is a true open source project:
Much more information at:
http://golang.org
https://tour.golang.org/welcome/1
shameless self promotion - Golang and IOT
https://www.elastic.co/products/beats
https://eng.uber.com/go-geofence/
React native + Go for mobile
http://marcio.io/2015/07/handling-1-million-requests-per-minute-with-golang/
http://www.slideshare.net/SergeyLanzman/gett-golang
Go and Data science - Daniel whitenack
Inroduction to golang

Inroduction to golang

  • 1.
    Introduction to Golang SpeakYour Way, February 1, 2017 Yoni Davidson Sears Israel
  • 2.
    From Wikipedia -What is Go Go (often referred to as golang) is a free and open source[12] programming language created at Google[13] in 2007 by Robert Griesemer, Rob Pike, and Ken Thompson. [10] It is a compiled, statically typed language in the tradition of Algol and C, with garbage collection, limited structural typing,[3] memory safety features and CSP-style concurrent programming features added.[14]
  • 3.
    Hello, world package main import"fmt" func main() { fmt.Printf("Hello, 世界n"); } Taken from: https://talks.golang.org/2009/go_talk-20091030.pdf
  • 4.
    Who Robert Griesemer, KenThompson, and Rob Pike started the project in late 2007. By mid 2008 the language was mostly designed and the implementation (compiler, run-time) starting to work. Ian Lance Taylor and Russ Cox joined in 2008. Lots of help from many others (Open source). Taken from: https://talks.golang.org/2009/go_talk-20091030.pdf
  • 5.
    Why Go fast! Makeprogramming fun again. There is focus on building client/server systems. Clusters can be massive. The rise of multi-core CPUs. Major system languages were not designed with all these factors in mind. Taken from: https://talks.golang.org/2009/go_talk-20091030.pdf
  • 6.
    Construction speed Takes toolong to build software. Tools are slow. Dependencies management is hard. Machines stopped getting faster (Dramatically). Taken from: https://talks.golang.org/2009/go_talk-20091030.pdf
  • 7.
    Type system Clunky typing:Taints good idea with bad implementation. Makes programming harder (think of C's const: well-intentioned but awkward in practice). Hierarchy is too stringent: Types in large programs do not easily fall into hierarchies. Programmers spend too much time deciding tree structure and rearranging inheritance. You can be productive or safe, not both. Taken from: https://talks.golang.org/2009/go_talk-20091030.pdf
  • 8.
    Why a newlanguage? These problems are endemic and linguistic. New libraries won’t help. (Adding anything is going in the wrong direction.) Need to start over, thinking about the way programs are written and constructed. Taken from: https://talks.golang.org/2009/go_talk-20091030.pdf
  • 9.
    Goals The efficiency ofa statically-typed compiled language with the ease of programming of a dynamic language. Safety: type-safe and memory-safe. Good support for concurrency and communication. Efficient, latency-free garbage collection. High-speed compilation. Taken from: https://talks.golang.org/2009/go_talk-20091030.pdf
  • 10.
  • 11.
  • 12.
    Where can wefind go? Traditionally in server side infrastructure (High query rate servers, Web crawlers): Some well known CLI/Server projects.
  • 13.
    Where can wefind go? IOT devices: Mobile:
  • 14.
    Go best advantages: Golangcompiles natively to most important architectures (arm, x86). Development is faster in comparison to C ,C++ Java. Deployment of code on ServerpcIOT is simple due to the nature of static compilation. Context switch between backend and device is simpler if you use go in both. Concurrency is easily used in go (in comparison to C/C++/java) lets you better exploit multi core architectures (very common today).
  • 15.
    Go best advantages: Nofile system dependency (Java , Nodejs, C++ - boost) - Code runs natively. Large and growing collection of open source code for large range of abilities. Compiles easily with C.
  • 16.
    Internal tools ingo build compile packages and dependencies clean remove object files doc show documentation for package or symbol env print Go environment information fix run go tool fix on packages fmt run gofmt on package sources generate generate Go files by processing source get download and install packages and dependencies install compile and install packages and dependencies list list packages run compile and run Go program test test packages tool run specified go tool version print Go version vet run go tool vet on packages
  • 17.
    Example simple webserver: package main import ( "fmt" "http" ) func handler(c *http.Conn, r *http.Request) { fmt.Fprintf(c, "Hello, %s.", r.URL.Path[1:]) } func main() { http.ListenAndServe(":8080", http.HandlerFunc(handler)) } https://talks.golang.org/2010/ExpressivenessOfGo-2010.pdf
  • 18.
    Structs type Point struct{ x, y float } func (p Point) Abs() float { return math.Sqrt(p.x*p.x + p.y*p.y) } Structs describe (and control) the layout of data. Methods are not mixed with the data definition. They are orthogonal to types. https://talks.golang.org/2010/ExpressivenessOfGo-2010.pdf
  • 19.
    Methods Orthogonality of methodsallows any type to have them. type Vector []float func (v Vector) Abs() float { sumOfSquares := 0.0 for i := range v { sumOfSquares += v[i]*v[i] } return math.Sqrt(sumOfSquares) } It also allows receivers to be values or pointers: func (p *Point) Scale(ratio float) { p.x, p.y = ratio*p.x, ratio*p.y } func swap(x, y string) (string, string) { //multiple results return y, x }
  • 20.
    Interfaces Interfaces are justsets of methods. work for any type. type Abser interface { Abs() float } var a Abser a = Point{3, 4} print(a.Abs()) a = Vector{1, 2, 3, 4} print(a.Abs()) Interfaces are satisfied implicitly. Point and Vector do not declare that they implement Abser, they just do!
  • 21.
    Error handling Functions oftenreturn an error value, and calling code should handle errors by testing whether the error equals nil. type error interface { Error() string }
  • 22.
    Error handling -example type MyError struct { When time.Time What string } func (e *MyError) Error() string { return fmt.Sprintf("at %v, %s", e.When, e.What) } func run() error { return &MyError{ time.Now(), "it didn't work", } } func main() { if err := run(); err != nil { fmt.Println(err) } }
  • 23.
    Concurrency Go's approach toconcurrency differs from the traditional use of threads and shared memory. Philosophically, it can be summarized: Don't communicate by sharing memory; share memory by communicating. Goroutines A goroutine is a function that is capable of running concurrently with other functions. To create a goroutine we use the keyword go followed by a function invocation. Channels Channels provide a way for two goroutines to communicate with one another and synchronize their execution.
  • 24.
    Go concurrency basics Starta goroutine: go f() Channel send (arrow points in direction of flow): ch <- value Channel receive: value = <-ch Channels are unbuffered by default, which combines synchronization with communication.
  • 25.
    Launching a goroutine Starta service, return a channel to communicate with it: package main func main() { // create new channel of type int ch := make(chan int) // start new anonymous goroutine go func() { // send 42 to channel ch <- 42 }() // read from channel <-ch }
  • 26.
    1. package main 2.import "time" 3. func main() { 4. var Ball int 5. table := make(chan int) 6. go player(table) 7. go player(table) 8. table <- Ball 9. time.Sleep(1 * time.Second) 10. <-table 11. } 12. func player(table chan int) { 13. for { 14. ball := <-table 15. ball++ 16. time.Sleep(100 * time.Millisecond) 17. table <- ball 18. } 19. }
  • 27.
    Closures are justlocal functions func Compose(f, g func(x float) float) func(x float) float { return func(x float) float { return f(g(x)) } } Closures
  • 28.
    Closures and concurrency Queryservers in replicated database, return first response. func Query(conns []Conn, query string) Result { ch := make(chan Result, 1) // buffer of 1 item for _, conn := range conns { go func(c Conn) { _ = ch <- c.DoQuery(query) }(conn) } return <-ch }
  • 29.
    This is atrue open source project: Much more information at: http://golang.org https://tour.golang.org/welcome/1 shameless self promotion - Golang and IOT https://www.elastic.co/products/beats https://eng.uber.com/go-geofence/ React native + Go for mobile http://marcio.io/2015/07/handling-1-million-requests-per-minute-with-golang/ http://www.slideshare.net/SergeyLanzman/gett-golang Go and Data science - Daniel whitenack