Top Banner
Go, Goroutines e o Gopher Alexandre Vicenzi
20

Go, goroutines e o gopher

Jan 16, 2017

Download

Technology

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Go, goroutines e o gopher

Go, Goroutines e o GopherAlexandre Vicenzi

Page 2: Go, goroutines e o gopher

O que é Go?Go é uma linguagem de programação desenvolvida pela Google para ajudar a resolver problemas do Google.

Page 3: Go, goroutines e o gopher

Origem● 2007 - 2009● Google● Robert Griesemer, Rob Pike e Ken Thompson

Page 4: Go, goroutines e o gopher

Proposta● Concorrente● Compilar rapidamente● Garbage Collector● Estaticamente tipada

Page 5: Go, goroutines e o gopher

Quem está usando?

Page 6: Go, goroutines e o gopher

Hello World

import “fmt”

func main() {

fmt.Println(“Olá mundo!”)

}

Page 7: Go, goroutines e o gopher

Diferenciais● Orientação a Objetos sem herança● Sem exceções● Imports e variáveis não usadas causam erro de compilação● Sem method overloading ou parâmetros opcionais● Visibilidade é definida pela primeira letra● Interfaces sem declaração (duck typing)

Page 8: Go, goroutines e o gopher

Sem exceçõesimport ( "os" "log")

file, err := os.Open("file.txt")

if err != nil { log.Fatal(err)}

Page 9: Go, goroutines e o gopher

Duck typingEm linguagens dinâmicas como Python existem o conceito de Duck Typing.

"if it looks like a duck and quacks like a duck, it’s a duck."

class Duck: def quack(self): print("quack")

class Cow: def quack(self): print("muu")

def say_quack(quacker) quacker.quack()

say_quack(Duck())say_quack(Cow())

Page 10: Go, goroutines e o gopher

Duck Typing em Go

type Duck struct {}

func (d *Duck) Quack() { fmt.Println("Quack")}

func SayQuack(q Quacker) { q.Quack()}

SayQuack(&Duck{})SayQuack(&Cow{})

type Cow struct {}

func (c *Cow) Quack() { fmt.Println("Muu")}

type Quacker interface { func Quack()}

Page 11: Go, goroutines e o gopher

Concorrência● Goroutines● Channels

Page 12: Go, goroutines e o gopher

Goroutines● Função que executa concorrentemente● São basicamente threads● Basta adicionar a keyword go na chamada do método● Muito similar ao comando & do shell, executa e termina silenciosamente

Page 13: Go, goroutines e o gopher

Goroutinesfunc f(from string) {

for i := 0; i < 3; i++ {

fmt.Println(from, ":", i)

}

}

func main() {

f("direct")

go f("goroutine")

go func(msg string) {

fmt.Println(msg)

}("going")

var input string

fmt.Scanln(&input)

fmt.Println("done")

}

$ go run goroutines.godirect : 0direct : 1direct : 2goroutine : 0goinggoroutine : 1goroutine : 2<enter>done

Page 14: Go, goroutines e o gopher

Channels● São pipes que conectam goroutines● Simples para trocar mensagens entre goroutines● Unbuffered e síncrono por padrão● O sender fica bloqueado até o receiver receber o valor● Buffered channels bloqueiam apenas se o buffer ficar cheio

Page 15: Go, goroutines e o gopher

Channelspackage main

import "fmt"

func main() {

messages := make(chan string)

go func() { messages <- "ping" }()

msg := <-messages

fmt.Println(msg)

}

$ go run channels.go ping

Page 16: Go, goroutines e o gopher

E mais● Ponteiros● Pacotes● Defer, Panic e Recover● Testes● Controle de dependências● C? Go? Cgo!

Page 17: Go, goroutines e o gopher

E o Gopher?Você já conheceu ele :)

● Desenhado por Renée French● Inspirado no gopher de uma promoçao de camisa da rádio WFMU

Page 18: Go, goroutines e o gopher

Dúvidas?

Page 19: Go, goroutines e o gopher

Referências● The Go Programming Language● Go by Example● An Introduction to Programming in Go

Page 20: Go, goroutines e o gopher

Obrigado

@alxvicenzi

alexandrevicenzi.com

github.com/alexandrevicenzi