Golang preso

15
This is what our presentations should look like JAN. 2, 2015 Go: Concurrency is Built In MAY 14,, 2015

Transcript of Golang preso

Page 1: Golang preso

This is what our presentations

should look like

JAN. 2, 2015

Go: Concurrency

is Built In

MAY 14,, 2015

Page 2: Golang preso

What’s Similar?GOLANG vs PYTHON

Page 3: Golang preso

Similarities with Python

• Can be “imperative” or “object-oriented”• Great for writing web servers (guess what my day job is)• Arrays use Python-like slicing• Easy iteration over arrays (lists) and maps (dicts) using range• Multiple return values from functions• Package management (go get vs. pip install)• Anonymous functions

3

Page 4: Golang preso

What’s Different?GOLANG vs PYTHON

Page 5: Golang preso

Differences with Python

• Structs vs. objects• Strongly-typed• Compiled, C-like syntax (ugh)• Interface vs inheritance• Modules vs. packages• camelCase• CapitalName : capitalName :: attribute : _attribute• return errors instead of raising exceptions

5

Page 6: Golang preso

Go has no GILGOLANG vs PYTHON

Page 7: Golang preso

It’s not bolted on like asyncio, or hacked in à la Tornado.

The Go runtime has a scheduler that automatically schedules multiple concurrent operations efficiently and automatically.

It’s so efficient, it doesn’t even guarantee all concurrent operations even run!

Concurrency is built into the runtime

7

Page 8: Golang preso

Concurrency

• goroutines• defer• wait groups (via sync package)• channels

8

Page 9: Golang preso

Everything in Go is a “goroutine”, including main(). Dispatch a function to execute in a separate goroutine using the go keyword:func doStuff(string a) { fmt.Println(a)}

func main() { var a string = “Python is cool!” go doStuff(a)}

goroutines

9

Page 10: Golang preso

You can defer execution of a line until the end of a function:func processFile(string filename) bool, error {

f, err := os.Open(filename)defer f.close()if err != nil {

return false, err}...return true, nil

}

defer

10

Page 11: Golang preso

Fire off multiple goroutines, wait until they are done before moving on:var wg sync.WaitGroupvar urls = []string{

"http://www.golang.org/","http://www.google.com","http://www.somestupidname.com/",

}for _, url := range urls {

wg.Add(1)go func(url string) {

defer wg.Done()http.Get(url)

}(url)}wg.Wait()

wait group

11

Page 12: Golang preso

Allow communication/synchronization between goroutines:func pinger(c chan string) {

for i := 0; ; i++ {

c <- "ping"

}

}

func printer(c chan string) {

for {

msg := <- c

fmt.Println(msg)

time.Sleep(time.Second * 1)

}

}

channels

12

func main() {

var c chan string = make(chan string)

go pinger(c)

go printer(c)

var input string

fmt.Scanln(&input)

}

Page 13: Golang preso

13

“Object-oriented design is the roman numerals of computing.”GOLANG DESIGNER ROB PIKE

Page 14: Golang preso

Use the best tool for the job.MY ADVICE:

Page 15: Golang preso

http://tour.golang.orgSTART HERE