¿Why Go? – ¿Por qué Go?



¿Why Go? – ¿Por qué Go?

0 0


por-que-go

Presentación de Go para el meet de GoMad 04/02/2014

On Github victorcoder / por-que-go

¿Why Go?

¿Por qué Go?

Victor Castell

@victorcoder

Minds behind

Rob Pike: Unix, Plan 9

Ken Thompson: Unix, Plan 9, B and C

Russ Cox: Plan 9, RE2

Robert Griesemer: V8, Java VM

Brad Fitzpatrick, Andrew Gerrand + lots of contributors

Precedents

Need for high-level programming in Unix

C++ became popular in the industry and research

Java - easy C++

Consecuences

C++ and Java are hard to use

Verbose and difficult to read, IDE required

We need "patterns" to address it's difficulty

Widely adopted today

Performant

Reaction

Bad developer experience

emerged

Python, Ruby, Lua, JavaScript, Erlang

beautiful

Scala, Haskell

Golden era

Why this popularity?

Outsiders are dynamic

ease of use != dynamic

The good

Efficcient, performat and safe

Very powerful in expert hands

Really big systems are built on them

Adapts well to corporate environments: lots of coders, big systems

The bad

Not developer friendly

Slow compilers and huge binaries

Programmers avoid

Old and not suitted to multicore

JVM have limits in memory management

Dynamic

Don't have the downsides

Less keystrokes because of dinamyc typing

No compile time

But they also have the "bad":

  • Slow
  • Not type-safe (static errors occur at runtime)
  • Doesn't scale well
  • They're also not very modern (+10 years)

We need you superman!

We need the good, without the bad, and multicore:

statically typed

fast execution, fast compilers

light and easy to write

fast to work in

scales well

doesn't require tools, but supports them well

good at networking and multiprocessing

Enter Go

Fun, efficient and open source

Statically typed and compiled, but it feels lightweight and dynamic

Designed for modern computing (multicore)

Aimed at software such as webservers, but turned out to be a great general-purpose language

Hello World 2.0

          //Serving http://localhost:8080/world:
          package main

          import (
            "fmt"
            "net/http"
            "log"
          )

          func main() {
            http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
              fmt.Fprintf(w, "Hello, %q", r.URL.Path[1:])
            })

            log.Fatal(http.ListenAndServe(":8080", nil))
          }
          

Highlights

Multiple return values

            func foo() int, string {
              return 1, "OK"
            }
            

Named return parameters

            func foo() (bar int){
              bar = 2+2
              return
            }
            

Variadic input parameters

            func Greeting(prefix string, who ...string)
            Greeting("hello:", "Joe", "Anna", "Eileen")
          
who, will have the value
[]string{"Joe", "Anna", "Eileen"}

Supports functional programming

first class functions

user-defined function types

function literals and closures

Closures are just local functions

            func foo(f func()) {
              x := f()

              func() {
                println(x)
              }()
            }
          

Features

Type inference

foo := "This is a string type"

Interfaces

            type Foo interface {
              privateMethod() int
              PublicMethod() int
            }
          

Features

Interfaces are satisfied implicitly, every type that implements it's methods is satisfying the interface

This is very powerful!

Concurrency basics

Start a goroutine

go f()

Channel sends

ch <- value

Channel receive

value = <-ch

Starting a goroutine

              func (s *Service) Start() chan request {
                ch := make(chan request)
                go s.serve(ch)  // s.serve runs concurrently
                return ch       // returns immediately
              }
            

Dependency management

Dependencies are expressed in source code

import "github.com/bmizerany/pat"

Two purposes, import path and library repository

Just push your code to a public repository

The "go get" command download and install all rependencies

Easy to define, easy to use

Other Features

Emphasis on simplicity

Garbage collected

Memory layout control (pointers but no pointer arithmetic)

Consistent standard library

Integrated testing

Ultra fast compiler (can be used as scripting language)

Target i386, amd64, arm (Mobile development)

But.. as any respected language also has dramas!

Status

Go 1 released 28/03/2012

Easy installation: Binaries for OSX, Linux, Windows

Stable, mature and suitable for real world problems

Used in production at big companies

Very active community and growing fast

Erlang vs Scala vs Go

Erlang and Scala implements the Actor model, Go implements goroutines

Scala has thread based Actors that are heavyweight

goroutines are lightweight, threads are heavy

All three models uses channels for messages

In Scala passing around primitive data like integers is expensive because of the JVM legacy

The inevitable comparison

node.js/JS/V8 doesn't have concurrency features but comparable for server programming

Awesome standard lib but not enought

Go stdlib, http, templates, websockets, tar/zip, json, xml, sql, smtp, etc...

node code is by definition non-blocking and asynchronous

Go let's you write synchronous looking code which behaves like if it were asynchronous, without requiring you to handle the callback spaghetti

Many libs in Go stdlib are non-blocking

The inevitable comparison

Fibonacci sequence made by the infamous post http://teddziuba.com/2011/10/node-js-is-cancer.html

node.js

            var http = require('http');

            function fibonacci(n) {
              if (n < 2)
                return 1;
              else
                return fibonacci(n-2) + fibonacci(n-1);
            }

            http.createServer(function (req, res) {
              res.writeHead(200, {'Content-Type' : 'text/plain'});
              res.end(fibonacci(40) + '');
            }).listen(1337);
          

The inevitable comparison

Go

            package main

            import (
              "fmt"
              "net/http"
              "log"
            )

            func fibonacci(n int) (result int) {
              if n < 2 {
                result = 1
              } else {
                result = fibonacci(n-2) + fibonacci(n-1)
              }
              return
            }

            func main() {
              http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
                w.Write([]byte(fmt.Sprintf("%d", fibonacci(40))))
              })

              log.Fatal(http.ListenAndServe(":8080", nil))
            }
          

Show me the numbers!

node.js 0.10.16

          time curl http://localhost:1337
          165580141
          real    0m2.097s
          user    0m0.007s
          sys     0m0.005s
          

Go 1.2

          time curl http://localhost:8080
          165580141
          real    0m1.323s
          user    0m0.007s
          sys     0m0.005s
          

Projects using Go

Docker

Martini

Vitess

Serf

InfluxDB

Mandala

Personal

guard-go

Trend

Toukei

HTTP proxies

Elasticsearch indexer

YOU

More information at golang.org

Play in the browser play.golang.org

Thanks!

@victorcoder