inroduction to golang

30
Introduction to Golang Speak Your Way, February 1, 2017 Yoni Davidson Sears Israel

Upload: yoni-davidson

Post on 13-Apr-2017

123 views

Category:

Software


0 download

TRANSCRIPT

Introduction to GolangSpeak Your Way, February 1, 2017

Yoni Davidson

Sears Israel

From Wikipedia - What is GoGo (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, worldpackage main

import "fmt"

func main() {

fmt.Printf("Hello, 世界\n");

}

Taken from: https://talks.golang.org/2009/go_talk-20091030.pdf

WhoRobert 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

WhyGo 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 speedTakes 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 systemClunky 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 Server\pc\IOT 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

Structstype 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

MethodsOrthogonality 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

}

InterfacesInterfaces 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 notdeclare that they implement Abser, they just do!

Error handlingFunctions 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 - exampletype 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)

}

}

ConcurrencyGo'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.

GoroutinesA 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.

ChannelsChannels provide a way for two goroutines to communicate with one another and synchronize their execution.

Go concurrency basicsStart 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

}

A common pattern, given channels as first-class values.

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

}