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
[]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
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
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
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
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
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
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 • …