Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Ulule Golang

Sponsored · Your Podcast. Everywhere. Effortlessly. Share. Educate. Inspire. Entertain. You do you. We'll handle the rest.
Avatar for thoas thoas
December 11, 2015
110

Ulule Golang

Avatar for thoas

thoas

December 11, 2015
Tweet

Transcript

  1. & • Typage statique • Un langage simple à apprendre

    • Une syntaxe claire et lisible (coucou Scala) • Un compilateur strict • Allocation de la mémoire automatique • Garbage collector 1
  2. 1 package main import "fmt" // typage func iter(max int)

    int { // instanciation d'une variable, automatiquement typée sum := 0 // ou instanciation manuelle var sum = 0 for i := 0; i < max; i++ { sum += i } return sum } func main() { fmt.Println(iter(10)) } Structure de contrôle
  3. % • Pas de while • Pas de valeur par

    défaut pour les paramètres
  4. 1 package main import "fmt" type Countries struct { data

    []string // tableau contenant des strings } // Methode Contains affectée à la structure // la capitale est nécessaire pour rendre publique la méthode func (c Countries) Contains(country string) bool { // Pas de methode "contains", iteration obligée :) for _, item := range c.data { if item == country { return true } } return false } func main() { store := &Countries{data: []string{"CA", "FR"}} fmt.Println(store.Contains("FR")) // true } Struct, méthodes et slices
  5. 1 package main import "fmt" type Countries struct { data

    map[string]string // tableau associatif contenant les labels } // Methode Contains affectée à la structure // la capitale est nécessaire pour rendre publique la méthode func (c Countries) Contains(code string) bool { _, found := c.data[code] return found } func (c Countries) Codes() []string { codes := []string{} for _, code := range c.data { codes = append(codes, code) } return codes } func main() { store := &Countries{data: map[string]string{"CA": "Canada", "FR": "France"}} fmt.Println(store.Contains("FR")) // true fmt.Println(store.Codes()) // [Canada France] } Maps
  6. 1 package main import "fmt" type DataStore interface { Contains(code

    string) bool } type Countries struct { data map[string]string // tableau associatif contenant les labels } func (c Countries) Contains(code string) bool { _, found := c.data[code] return found } func Contains(store DataStore, value string) bool { return store.Contains(value) } func main() { store := &Countries{data: map[string]string{"CA": "Canada", "FR": "France"}} // Countries implemente la méthode Contains // et donc l'interface DataStore implicitement // store peut donc être passé en paramètre fmt.Println(Contains(store, "FR")) } interfaces
  7. 1 package main import ( "fmt" "time" ) 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) } } Gestion des erreurs
  8. & • Une standard library riche • Prévu pour le

    web (net/http) • Le langage du cloud • Des outils présents dans le langage 2
  9. 2 package main import "fmt" func main() { defer fmt.Println("world")

    fmt.Println("hello") } $ go run hello.go hello world Du fun, je te dis !
  10. 2 package main import ( "fmt" "log" "net/http" ) type

    Hello struct{} func (h Hello) ServeHTTP( w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "Hello!") } func main() { var h Hello err := http.ListenAndServe("localhost:8000", h) if err != nil { log.Fatal(err) } } Un serveur web
  11. 2 package main import "fmt" // func return type func

    intSeq() func() int { i := 0 return func() int { i += 1 return i } } func main() { // retourne une function nextInt := intSeq() fmt.Println(nextInt()) newInts := intSeq() fmt.Println(newInts()) } Closures
  12. 2 Les outils : plein, épuisant • gofmt formatter son

    code automatiquement • golint vérifier les erreurs de programmation • go get installer une librairie et ses dépendances • benchcmp extraire les allocations, la vitesse à partir des tests
  13. & • Léger • Concurrent sans vous rendre fou •

    Très haut niveau • Rapide à la compilation • Rapide à l’execution 3
  14. 3 package main import ( "fmt" "time" ) func say(s

    string) { for i := 0; i < 5; i++ { time.Sleep(100 * time.Millisecond) fmt.Println(s) } } func main() { go say("world") say("hello") } Goroutines
  15. 3 package main import "fmt" func sum(a []int, c chan

    int) { sum := 0 for _, v := range a { sum += v } c <- sum // send sum to c } func main() { a := []int{7, 2, 8, -9, 4, 0} c := make(chan int) go sum(a[:len(a)/2], c) go sum(a[len(a)/2:], c) x, y := <-c, <-c // receive from c fmt.Println(x, y, x+y) } Canaux
  16. 3 package main import ( "fmt" "time" "runtime" ) const

    NUM_JOBS = 9 func worker(id int, jobs <-chan int, results chan<- int) { for j := range jobs { fmt.Println("worker", id, "processing job", j) time.Sleep(time.Second) results <- j * 2 } } func main() { jobs := make(chan int, 100) results := make(chan int, 100) // Instancier autant de worker que de core for w := 1; w <= runtime.NumCPU(); w++ { go worker(w, jobs, results) } for j := 1; j <= NUM_JOBS; j++ { jobs <- j } close(jobs) // On recupere tous les resultats for a := 1; a <= NUM_JOBS; a++ { <-results } Goroutines + canaux = worker pools
  17. 3 package main import ( "strconv" "sync" ) type Currency

    struct { sync.Mutex amount float64 code string } func (c *Currency) Set(i float64) { c.Lock() c.amount = i c.Unlock() } func (c *Currency) Display() string { c.Lock() defer c.Unlock() return strconv.FormatFloat(c.amount, 'f', 2, 64) + " " + c.code } Mutexes
  18. , Aller plus loin • An incomplete list of go

    tools • Tools for working with Go Code • How goroutines work • Effective Go • Go by example • Go talks • Handling 1 Million Requests per Minute • Building web apps with Go • …
  19. ?