class: center, middle # Go A Perspective ### Presented by Gábor Lipták --- # Agenda 1. Introduction 1. Highlights 1. Links 1. Q & A --- # What can you expect from this presentation? I will offer highlights of Go features anchoring them onto other languages like C, Java, Python, etc. About me: I work as an architect, using Java, Python day-to-day and used and/or studied C/C++, Smalltalk, Erlang, Haskell, Go and other programming languages About you: You bring coding background and your questions (feel free to ask them during the presentation). Those with Go background, please offer suggestions on how this presentation can be improved. --- # Why (learn) Go? Most software projects have server-side scalability needs, but the paradigms offered by most mainstream languages are hard to code (correctly) and hard to reason about. Go's built-in concurrency helps, as [real world examples](https://github.com/golang/go/wiki/SuccessStories) show. [Anecdotal comments (from iron.io which posted the first commercial Go job posting)](https://www.iron.io/how-we-went-from-30-servers-to-2-go/): "After we rolled out our Go version, we reduced our server count (from 30) to two and we really only had two for redundancy. They were barely utilized, it was almost as if nothing was running on them. Our CPU utilization was less than 5% and the entire process started up with only a few hundred KB’s of memory (on startup) vs our Rails apps which were ~50MB (on startup)." --- # Obligatory Hello World! ```go package main import "fmt" func main() { str := "Hello, 世界" fmt.Println(str) } ``` [hello1.go](hello1.go) --- # A better C(++) (!?) Developed at Google by [Rob Pike (Plan 9 at Bell Labs, Sawzall)](https://en.wikipedia.org/wiki/Rob_Pike), [Ken Thompson (UNIX at Bell Labs, UTF-8)](https://en.wikipedia.org/wiki/Ken_Thompson), [Robert Griesemer (Sawzall, V8, StrongTalk at Google Research)](http://research.google.com/pubs/author96.html), [Ross Cox (Plan 9)](http://research.swtch.com/) and others. Project initiated in 2007, open sourced in 2009 Used by Google (Kubernetes, internal projects), Docker, CoreOS, Dropbox, Heroku, Atlassian, Brightcove, eBay, Facebook, Booking.com, Netflix, Newrelic, Github and [numerous others](https://github.com/golang/go/wiki/GoUsers) --- # Highlights 1/2 * General purpose * Made to Top 10 Repository Languages on Github https://octoverse.github.com/ http://githut.info/ * [Top 5 Most Loved Language](http://stackoverflow.com/research/developer-survey-2016#technology-most-loved-dreaded-and-wanted) * Development happens in the open (mailing lists, Github) * Pragmatic and expressive feature choices * Influenced by Oberon (look-and-feel), Smalltalk (object system), NewSqueak (concurrency) * Orthogonal language features (principle of least surprise) * Standard library (batteries included, in particular networking, crypto, JSON) * Compact language (25 reserved keywords) * Garbage collected (soft guarantee) * Statically typed * Type-safe and memory safe (unless unsafe package is used) * Cross compiles to Linux/Windows/x86/ARM * Concurrency built into the language ??? 30 keywords for C No operator/keyword overload No generics --- # Highlights 2/2 * Simple syntax (no semicolons in particular, curly braces required for if/for) * Object (but not type) oriented (see interfaces) * Functions are first class objects (but no tail recursion) * Compile efficiently at scale, no transitive dependency loading * Statically linked (while fatter binaries, single artifact to worry about) * De facto formatting (with tabs :) ) using gofmt (also used as API updater gofix) * Handling exceptional situations --- # Another Example ```go package main import ( "net/http" "fmt" ) func hello(w http.ResponseWriter, r *http.Request) { p := r.URL.Path[1:] if len(p) == 0 { p = "root" } fmt.Fprintf(w, "Hi there, loading %s!", p) } func monkey(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello Monkey!") } func main() { http.HandleFunc("/", hello) http.HandleFunc("/monkey", monkey) http.ListenAndServeTLS(":10443", "cert.pem", "key.pem", nil) } ``` [webserver1.go](webserver1.go) --- # Built-in types * bool * int/uint (8/16/32/64) * float (32/64) * complex (64/128) * string * array/slice * struct * pointer * function * interface * map * channel ??? Note sizes, and also map, function and channel as built-ins --- # Named types * Let the compiler tell you that parameters were mixed up [namedtype1.go](namedtype1.go) ??? Not frequently highlighted --- # Closures * Similar to most modern languages [fibonacci1.go](fibonacci1.go) ??? There is a saying in computer science that a class is "data with operations attached" while a closure is "operations with data attached." --- # Interfaces 1/2 * If a type implements all methods of an interface, then it implements the interface * There is no hierarchy of interfaces * Interfaces are often introduced during codebase refactoring * No generics --- # Interfaces 2/2 ```go type Stringer interface { String() string } type Reader interface { Read(p []byte) (n int, err error) } type Writer interface { Write(p []byte) (n int, err error) } ``` * All types implement the empty interface (`interface{}`) * Methods can be implemented on any type (including built-in types) [writer1_test.go](writer1_test.go) ??? `implements` not required like in Java Think "monkey-patching" in Ruby No parametric polymorphism --- # Reflection * Type information is available and can be queried runtime * Used by standard Go libraries like [JSON](https://github.com/golang/go/tree/master/src/encoding/json) [reflect1.go](reflect1.go) --- # Testing The `go test` command will look for any tests in any of the files in the current folder and run them. ```go func TestAddition(t *testing.T) ``` [sample1_test.go](sample1_test.go) --- # Go Routines and Channels * A go call turns a function (closure) invocation into a goroutine * Channels support concurrent processing using message passing (like Joe Armstrong's Erlang metaphor) * Channels are shared memory FIFO queues with syncronized operations (buffered or unbuffered) * For a lot of simple goroutines, the 2 kB stack is probably more than necessary, which means you can run hundreds of thousands of go routines on desktop hardware (although worker pools might be the preferred approach in most cases). Contrast this to C threads, where 64 kB is a tiny stack and 1-4 MB is more common. ??? Discuss Unix fork, Actors (Erlang in particular, immutable messages), Java threads, Python asyncio/coroutines Actors serialize access to state Like & in Shell Don't communicate by sharing memory; instead share memory by communicating Erlang message passing is asynch/buffered, actors have identity vs Go channels have identity [Alan Kay OO missed out messaging](http://www.purl.org/stefan_ram/pub/doc_kay_oop_en) --- # Go Routines * Main function exits, the program stops [pingpong1.go](pingpong1.go) [fibonacci2.go](fibonacci2.go) --- # Mutexes * Channel best used for * Passing ownership of data * Distributing units of work * Communicating async results * Mutexes best used for * Caches * State * Don't be afraid to switch paradigms * Data race detector [mutex-counter1.go](mutex-counter1.go) [race1.go](race1.go) ??? Old habits die hard https://github.com/golang/go/wiki/MutexOrChannel https://golang.org/doc/articles/race_detector.html --- # Go Routines Select and Timeout * Select multiplexes channels (including timeout "pseudo" channels) * This is built-in into the language [timeout1.go](timeout1.go) --- # Handling exceptional situations * Standard library prefers to use `err` return values instead * Multiple return values and `nil` * Exceptions do feel like an afterthought ... * `panic` (think throw runtime error) * `recover` (function scoped catch) * `defer` (function scoped finally) [panic1.go](panic1.go) [panic2.go](panic2.go) --- # Packages / Build Times Package names based on folder names. Of course, if you are building from scratch and package A imports B which imports C, then of course C has to be compiled first, and then B, and then A. The import point is that when you go to compile A, you don’t reload C’s object file. In a real program, the dependencies are usually not a chain like this. We might have A1, A2, A3, and so on all importing B. It’s a significant win if none of them need to reread C. ??? Folder names are package names like in Java See http://xkcd.com/303/ --- # Links * https://tour.golang.org/list * https://play.golang.org/ * https://gobyexample.com/ * http://www.golang-book.com/books/intro * http://www.golangbootcamp.com/ * https://gowalker.org/ * http://gophervids.appspot.com/ * Search for Go (golang) presentation videos on http://youtube.com --- # The other side of the coin * http://yager.io/programming/go.html * http://dtrace.org/blogs/wesolows/2014/12/29/golang-is-trash/ --- # Q & A --- # Backup slide * http://marcio.io/2015/07/handling-1-million-requests-per-minute-with-golang/ * https://gist.github.com/harlow/dbcd639cf8d396a2ab73 * https://gobyexample.com/worker-pools * http://marcio.io/2015/07/cheap-mapreduce-in-go/ * https://gist.github.com/mcastilho/e051898d129b44e2f502 Cheap MapReduce in Go * http://devs.cloudimmunity.com/gotchas-and-common-mistakes-in-go-golang/ * https://github.com/mjibson/goread * http://www.goread.io/ * http://research.swtch.com/gotour * https://eventuallyconsistent.net/2014/10/16/go-is-boring/ * https://play.golang.org/p/ssVH6Rg3-Z FizzBuzz with channels * https://play.golang.org/p/lZtjYkD2dI Webcrawler * https://channel9.msdn.com/Events/Lang-NEXT/Lang-NEXT-2012/Go-In-Three-Easy-Pieces * http://www.cs.cmu.edu/~crary/819-f09/Hoare78.pdf * https://news.ntppool.org/2012/10/new-dns-server/ * https://github.com/ksimka/go-is-not-good * http://blog.ralch.com/tutorial/ * https://www.youtube.com/watch?v=0ReKdcpNyQg * https://youtu.be/f6kdp27TYZs * https://youtu.be/QDDwwePbDtw