GO Lang para
desenvolvedores
pragmáticos
Wilson Júnior
Wilson Júnior
Desenvolvedor
/Globocom/Rio/Backstage
Apaixonado por Tecnologia, Pessoas,
e aprender novas nerdices.
Motivação
Então!, o que é GO Lang ?
Criadores
Ken Thompson (1943)
● Former Bell Labs
● Googler
● Unix
● B (Programming language)
● UTF-8
Criadores
Rob Pike (1956)
● Googler
● Plan 9
● Inferno (Operating System)
● Limbo (Programming Language)
● UTF-8
Criadores
Robert Griesemer
● Googler
● V8 JavaScript engine;
● Sawzall (Linguagem de programação)
● Java HotSpot virtual machine
● Strongtalk system.
Softwares escritos em GO
Vamos começar o projeto
● Faça o fork do projeto em
github.com/wpjunior/go-course
● brew install go # 1.8
● Baixe seu projeto com `go get
github.com/SEU-USUARIO-GITHUB/go-cour
se`
Esperamos que vocês já tenham configurado o
projeto mais ou menos assim
Preparados ?!
Entre no diretório de batalha!
cd ~/go/src/github.com/SEU-GITHUB/go-course
Lesson 1 - Hello world
package main
import "fmt"
func main() {
fmt.Println("Olá nobre guerreiros!")
}
$ pushd 1-hello-world
# E veja o arquivo main.go
Running
# então execute
$ go run main.go
# assim para todos os
exemplos deste projeto
# após rodar volte para raíz
com:
$ popd
Conseguiram ?!
Parabéns guerreiros!
Variáveis
# já vão rodando um:
$ pushd 2-variables
Lesson 2 - Variáveis
Tipo de dado básico Exemplo
string "valor"
int 10
float64 3.14
bool true | false
● Os outros tipos veremos ao decorrer do curso
Lesson 2 - Variáveis - Exemplo
package main
import "fmt"
func main() {
// declarando uma variável utilizando o modelo pré
declarativo
var x int
x = 10
fmt.Printf("O valor de 'x' é %dn", x)
Lesson 2 - Variáveis
// declarando uma variável utilizando o modelo
auto-declarativo
a := 20
fmt.Printf("O valor de 'a' era %dn", a)
a = 30
fmt.Printf("O valor de 'a' agora é %dn", a)
Lesson 2 - Variáveis
// string
name := "wilson"
fmt.Println("Meu nome é", name)
// float64
pi := 3.14
fmt.Printf("O valor de PI é %0.6fn", pi)
// bool
verdade := true
mentira := false
fmt.Println("Verdade é igual a mentira:",
verdade == mentira)
}
Constantes
# já vão rodando um:
$ pushd 3-constantes
Lesson 3 - Constantes - Exemplo
package main
import "fmt"
const PI = 3.14
func main() {
fmt.Println("O valor de PI é", PI)
}
Funções
# já vão rodando um:
$ pushd 4-funcoes
Lesson 4 -Funções - Exemplo
package main
import "fmt"
func add(x int, y int) int {
return x + y
}
func main() {
fmt.Println("O resultado de 10 + 20 é", add(10, 20))
}
Funções públicas
e privadas
Lesson 4 -Funções - Exemplo Pública
package main
import "fmt"
func Add(x int, y int) int {
return x + y
}
func main() {
fmt.Println("O resultado de 10 + 20 é", Add(10, 20))
}
Funções:
parâmetros
continuados
Lesson 4 -Funções - Exemplo Parâmetros continuados
package main
import "fmt"
func Add(x, y int) int {
return x + y
}
func main() {
fmt.Println("O resultado de 10 + 20 é", Add(10, 20))
}
Funções:
Múltiplos
retornos
Lesson 4 -Funções - Exemplo Parâmetros continuados
package main
import "fmt"
func Add(x, y int) (int, int) {
return x + y, 0
}
func main() {
result, other := Add(10, 20)
fmt.Println("O resultado de 10 + 20 é", result)
fmt.Println("O parametro extra é", other)
}
Structs
# já vão rodando um:
$ pushd 5-structs
Lesson 5 - Structs - Exemplo
package main
import "fmt"
type Person struct {
Name string
Age int
Active bool
}
Lesson 5 - Structs - Exemplo
func main() {
p := Person{
Name: "Wilson Júnior",
Age: 24,
Active: true,
}
fmt.Println("Nome", p.Name)
fmt.Println("Age", p.Age)
fmt.Println("Active", p.Active)
}
Structs com
Ponteiros
Lesson 5 - Structs - Exemplo
func changePerson(p *Person) {
p.Age = 90
}
Lesson 5 - Structs - Exemplo
func main() {
p := &Person{
Name: "Wilson Júnior",
Age: 24,
Active: true,
}
changePerson(p)
fmt.Println("Nome", p.Name)
fmt.Println("Age", p.Age)
fmt.Println("Active", p.Active)
Structs …
experimentar ...
Lesson 5 - Structs - Exemplo
func main() {
p := &Person{Name: "Wilson Júnior"}
fmt.Println("Nome", p.Name)
fmt.Println("Age", p.Age)
fmt.Println("Active", p.Active)
}
Rodem e me
montrem-me suas
percepções ...
Arrays
# já vão rodando um:
$ pushd 6-arrays
Lesson 6 -Arrays - Exemplo
package main
import "fmt"
func main() {
var mandamentos [2]string
mandamentos[0] = "Amor"
mandamentos[1] = "Paz"
fmt.Println("Mandamentos: ", mandamentos)
}
One line
declaration
Lesson 6 -Arrays - Exemplo
package main
import "fmt"
func main() {
mandamentos := [2]string{"Amor", "Paz"}
fmt.Println("Mandamentos: ", mandamentos)
}
Desafio, faça um
array de int de
tamanho 3
Slices
# já vão rodando um:
$ pushd 7-slices
Lesson 6 - Slices - Exemplo
package main
import "fmt"
func main() {
linguagens := []string{"python", "ruby", "javascript"}
linguagens = append(linguagens, "go")
fmt.Println("Linguagens da globo.com: ", linguagens)
fmt.Println("Linguagens da globo.com: ", linguagens[1:3])
Lesson 6 - Slices - Exemplo
for i, linguagem := range linguagens {
fmt.Printf(
"Linguagem na posição %d do slice, valor: %sn",
i,
linguagem,
)
}
}
Criando slices
avançados com
make
Lesson 6 -Arrays - Exemplo
package main
import "fmt"
func main() {
linguagens := make([]string, 0, 5)
linguagens = append(linguagens, "go")
fmt.Println("Linguagens da globo.com: ", linguagens)
fmt.Println("Linguagens da globo.com: ", linguagens[1:3])
}
Maps
# já vão rodando um:
$ pushd 8-maps
Lesson 8 - Maps - Exemplo
package main
import "fmt"
func main() {
people := map[string]int{
"wilson": 25,
"andre": 26,
}
people["junior"] = 10
Lesson 8 - Maps - Exemplo
for name, age := range people {
fmt.Printf(
"Chave %s do mapa valor: %dn",
name,
age,
)
}
delete(people, "wilson")
fmt.Printf("Posição não alocada: %dn", people["wilson"])
}
Desafio, altere o
mapa para um
mapa de inteiro
para float64
Em 120 segundos
Métodos
# já vão rodando um:
$ pushd 9-methods
Lesson 9 - Métodos - Exemplo
package main
import "fmt"
type Person struct {
Name string
Age int
}
func (p *Person) String() string {
if p.Age < 18 {
return fmt.Sprintf("Olá jovem %s, seja bem vindo", p.Name)
} else if p.Age > 50 {
return fmt.Sprintf("Olá senhor %s, seja bem vindo", p.Name)
}
return fmt.Sprintf("Olá %s, seja bem vindo", p.Name)
Lesson 9 - Métodos - Exemplo
func main() {
person := Person{Name: "júnior", Age: 17}
fmt.Println(person.String())
person = Person{Name: "Wilson", Age: 27}
fmt.Println(person.String())
person = Person{Name: "Antônio", Age: 60}
fmt.Println(person.String())
}
Metódos
privados
Lesson 9 - Métodos - Exemplo
func (p *Person) privateMethod() int {
return p.Age * 4
}
Desafio, crie um
método privado e
o chame-o no
exemplo
Interfaces
# já vão rodando um:
$ pushd 10-interfaces
Lesson 11 - Interfaces - Exemplo
package main
import "fmt"
type Animal interface {
Shout() string
}
Lesson 11 - Interfaces - Exemplo
type Cow struct{}
func (c *Cow) Shout() string {
return "Muuu"
}
Lesson 11 - Interfaces - Exemplo
type Dog struct{}
func (d *Dog) Shout() string {
return "Rau rau!"
}
Lesson 11 - Interfaces - Exemplo
func main() {
var animal Animal
animal = &Cow{}
callMyAnimal(animal)
animal = &Dog{}
callMyAnimal(animal)
}
func callMyAnimal(a Animal) {
fmt.Println("My animal says:", a.Shout())
}
Desafio,
implemente um
nova struct para
a interface
Animal
Errors simples
# já vão rodando um:
$ pushd 11-errors
Errors são uma interface
type error interface {
Error() string
}
Lesson 11 - Interfaces - Exemplo
package main
import (
"errors"
"fmt"
)
// ErrNotAllowed é chamado quando o menor tem menos de 19 anos
var ErrNotAllowed = errors.New("Não permitida a entrada")
func entryInParty(age int) (string, error) {
if age < 18 {
return "", ErrNotAllowed
}
return "TICKET", nil
}
Lesson 11 - Interfaces - Exemplo
func main() {
ticket, err := entryInParty(17)
if err != nil {
fmt.Println("Falha ao entrar na Balada: ", err)
}
ticket, err = entryInParty(17)
if err == ErrNotAllowed {
fmt.Println("Chame os pais da criança!")
}
fmt.Println("Ticket liberado", ticket)
}
Lidar com dados
Genéricos
utilizando
interfaces vazias
Lesson 11 - Interfaces - Exemplo
func genericFunction(v interface{}) string {
switch v.(type) {
case string:
return "É uma string"
case int:
return "É um inteiro"
case float64:
return "É um ponto flutuante"
}
return "Não conheço"
}
Lesson 11 - Interfaces - Exemplo
func main() {
fmt.Println(genericFunction(10))
fmt.Println(genericFunction("wilson"))
fmt.Println(genericFunction(3.14))
}
Lesson 11 - Interfaces - Exemplo
https://play.golang.org/p/POpt4HYOBJ
Agora vocês já
sabem o que é
interfaces e
errors
Que tal conhecer
algumas
interfaces
famosas da
linguagem
Interfaces famosas da linguagem
package io
type Reader interface {
Read(p []byte) (n int, err error)
}
Interfaces famosas da linguagem
package io
type Writer interface {
Write(p []byte) (n int, err error)
}
Interfaces famosas da linguagem
package io
type Closer interface {
Close() error
}
Interfaces famosas da linguagem
package io
type ReadCloser interface {
Reader
Closer
}
Não se preocupe!, não
precisamos
implementar
nenhuma dessas
interfaces!
Interfaces famosas da linguagem
file, err := os.Open("myfile.txt")
# *os.File implementa várias interfaces do
pacote io
E se eu quiser usar a
memória ?!
Interfaces famosas da linguagem
buffer, err := bytes.NewBufferString("")
# *bytes.Buffer também implementa muitas
interfaces do pacote io
Common mistakes
over interfaces
Interfaces famosas da linguagem
func myFunction(file *os.File) {
file.Read()
}
Sempre que der utilize
interfaces, mas não
abuse!
Interfaces famosas da linguagem
func myFunction(r io.Reader) {
r.Read()
}
O que isso facilita ?!
Errors
estruturados
# já vão rodando um:
$ pushd 12-errors
Lesson 12 - Errors estruturados - Exemplo
package main
import "fmt"
type MyError struct {
Code int
Cause string
}
func (e *MyError) Error() string {
return fmt.Sprintf("Error %d", e.Code)
}
Lesson 12 - Errors estruturados - Exemplo
func doSomething() error {
return &MyError{
Code: 100,
Cause: "Unexpected ...",
}
}
Lesson 12 - Errors estruturados - Exemplo
func main() {
err := doSomething()
if myError, ok := err.(*MyError); ok {
fmt.Println("Code of error:", myError.Code)
fmt.Println("Cause of error:", myError.Cause)
}
}
Testes
# já vão rodando um:
$ pushd 13-tests
Biblioteca usada:
gopkg.in/check.v1
Lesson 12 - Testes - Exemplo
package main
type Calculator struct{}
func (*Calculator) Add(x, y int) int {
return x + y
}
Dado um simples código testável
Lesson 12 - Testes - Exemplo
func Test(t *testing.T) {
check.TestingT(t)
}
Plugando a library de test
Lesson 12 - Testes - Exemplo
type CalculatorSuite struct {
calculator *Calculator
}
Construindo a suite
Lesson 12 - Testes - Exemplo
var _ = check.Suite(&CalculatorSuite{})
Registrando a suite
Lesson 12 - Testes - Exemplo
func (s *CalculatorSuite) SetUpSuite(c *check.C) {
s.calculator = &Calculator{}
}
Definindo um before
Lesson 12 - Testes - Exemplo
func (s *CalculatorSuite) SetUpTest(c *check.C) {
// do something before each test
}
Definindo um beforeEach
Lesson 12 - Testes - Exemplo
func (s *CalculatorSuite) TestAddSuccess(c *check.C) {
result := s.calculator.Add(42, 10)
c.Check(result, check.Equals, 52)
}
func (s *CalculatorSuite) TestAddFail(c *check.C) {
result := s.calculator.Add(42, 10)
c.Check(result, check.Equals, 10)
}
Escrevendo testes
Lesson 12 - Testes - Exemplo
func (s *CalculatorSuite) TearDownTest(c *check.C) {
// do something after each test
}
Definindo um afterEach
Lesson 12 - Testes - Exemplo
func (s *CalculatorSuite) TearDownSuite(c *check.C)
{
// do something after test
}
Definindo um after
Execute o teste
$ go test .
Checkers
check.DeepEquals c.Assert(value, check.DeepEquals, expected)
check.Equals c.Assert(value, check.Equals, expected)
check.HasLen c.Assert(list, check.HasLen, 5)
check.Implements c.Assert(err, check.Implements, &e)
check.Not c.Assert(value, check.Not(check.Equals),
expected)
Desafio, implemente
alguma operação na
struct Calculator e seus
respectivos testes
Goroutines
# já vão rodando um:
$ pushd 14-goroutines
Como é a concorrência em Python ou Ruby
GIL
O que temos em máquinas nos nossos datacenters
Lesson 13 - Goroutine - Exemplo - Definindo uma function
func task(name string) {
for {
fmt.Println("Executing task", name)
time.Sleep(time.Second)
}
}
Lesson 13 - Goroutine - Exemplo - Criando as goroutinas
func main() {
go task("goroutine 1")
go task("goroutine 2")
go task("goroutine 3")
go task("goroutine 4")
go task("goroutine 5")
task("main")
}
Executem
Digam o que acharam
E para comunicar
com as goroutines ?
Channels
# já vão rodando um:
$ pushd 15-channels
Lesson 14 - Channels - Exemplo - Declarando uma função
func task(name string, channel chan int) {
for {
value := <-channel
fmt.Println("Executing task", value, "by", name)
}
}
Lesson 14 - Channels - Exemplo - Declarando uma função
func main() {
channel := make(chan int)
go task("goroutine 1", channel)
go task("goroutine 2", channel)
go task("goroutine 3", channel)
go task("goroutine 4", channel)
go task("goroutine 5", channel)
for i := 0; i < 100; i++ {
channel <- i
}
// wait all gorotines to finish
time.Sleep(time.Second)
}
Wilson!, eu posso
escutar vários
channels ao mesmo
tempo ?!
Lesson 14 - Channels - Exemplo
func myFunction(messages chan string, quit chan bool) {
for {
select {
case message := <-messages:
fmt.Println("message received: ", message)
case <-quit:
fmt.Println("closing the goroutine")
return
}
}
}
Lesson 14 - Channels - Exemplo - Declarando uma função
play.golang.org/p/cqhs6I1BDK
Usando essa mesma
estrutura podemos
implementar:
Timeouts!
Lesson 14 - Channels - Exemplo
package time
func After(d Duration) <-chan Time
Lesson 14 - Channels - Exemplo
func myFunction(messages chan string) {
for {
select {
case message := <-messages:
fmt.Println("message received: ", message)
case <-time.After(3 * time.Second):
fmt.Println("Timeout! closing the goroutine")
return
}
}
}
Lesson 14 - Channels - Exemplo
play.golang.org/p/rewSr5stiR
Mutexes
# já vão rodando um:
$ pushd 16-mutexes
Lesson 15 - Mutexes - Exemplo
type SafeMap struct {
m map[string]string
}
func (s *SafeMap) Set(key, value string) {
s.m[key] = value
}
func (s *SafeMap) Get(key string) string {
return s.m[key]
}
Lesson 15 - Mutexes - Exemplo
type SafeMap struct {
mutex sync.Mutex
m map[string]string
}
func (s *SafeMap) Set(key, value string) {
s.mutex.Lock()
defer s.mutex.Unlock()
s.m[key] = value
}
func (s *SafeMap) Get(key string) string {
s.mutex.Lock()
defer s.mutex.Unlock()
return s.m[key]
}
Wilson!, podemos
otimizar esta parada!
sync.RWMutex
Lesson 15 - Mutexes - Exemplo
type SafeMap struct {
mutex sync.RWMutex
m map[string]string
}
func (s *SafeMap) Set(key, value string) {
s.mutex.Lock()
defer s.mutex.Unlock()
s.m[key] = value
}
func (s *SafeMap) Get(key string) string {
s.mutex.RLock()
defer s.mutex.RUnlock()
return s.m[key]
}
WaitGroup
# já vão rodando um:
$ pushd 17-waitgroup
Lesson 17 - WaitGroup - Exemplo
type MultiWorker struct {
wg sync.WaitGroup
}
func (w *MultiWorker) Run() {
for i := 0; i < 100; i++ {
w.wg.Add(1)
go w.runJob(i)
}
w.wg.Wait()
}
Lesson 17 - WaitGroup - Exemplo
func (w *MultiWorker) runJob(id int) {
defer w.wg.Done()
defer fmt.Printf("Job %d finishedn", id)
if (id % 2) == 0 {
time.Sleep(time.Second)
} else {
time.Sleep(2 * time.Second)
}
}
Lesson 17 - WaitGroup - Exemplo
func main() {
w := &MultiWorker{}
w.Run()
}
Executem
Digam o que acharam
Obrigado, deêm seus
feedbacks!
Amanhã segundo
step do curso!

Go Lang para desenvolvedores pragmáticos (parte 1)

  • 1.
  • 2.
    Wilson Júnior Desenvolvedor /Globocom/Rio/Backstage Apaixonado porTecnologia, Pessoas, e aprender novas nerdices.
  • 3.
  • 4.
    Então!, o queé GO Lang ?
  • 5.
    Criadores Ken Thompson (1943) ●Former Bell Labs ● Googler ● Unix ● B (Programming language) ● UTF-8
  • 6.
    Criadores Rob Pike (1956) ●Googler ● Plan 9 ● Inferno (Operating System) ● Limbo (Programming Language) ● UTF-8
  • 7.
    Criadores Robert Griesemer ● Googler ●V8 JavaScript engine; ● Sawzall (Linguagem de programação) ● Java HotSpot virtual machine ● Strongtalk system.
  • 8.
  • 9.
    Vamos começar oprojeto ● Faça o fork do projeto em github.com/wpjunior/go-course ● brew install go # 1.8 ● Baixe seu projeto com `go get github.com/SEU-USUARIO-GITHUB/go-cour se` Esperamos que vocês já tenham configurado o projeto mais ou menos assim
  • 10.
  • 11.
    Entre no diretóriode batalha! cd ~/go/src/github.com/SEU-GITHUB/go-course
  • 12.
    Lesson 1 -Hello world package main import "fmt" func main() { fmt.Println("Olá nobre guerreiros!") } $ pushd 1-hello-world # E veja o arquivo main.go
  • 13.
    Running # então execute $go run main.go # assim para todos os exemplos deste projeto # após rodar volte para raíz com: $ popd
  • 14.
  • 15.
  • 16.
    Variáveis # já vãorodando um: $ pushd 2-variables
  • 17.
    Lesson 2 -Variáveis Tipo de dado básico Exemplo string "valor" int 10 float64 3.14 bool true | false ● Os outros tipos veremos ao decorrer do curso
  • 18.
    Lesson 2 -Variáveis - Exemplo package main import "fmt" func main() { // declarando uma variável utilizando o modelo pré declarativo var x int x = 10 fmt.Printf("O valor de 'x' é %dn", x)
  • 19.
    Lesson 2 -Variáveis // declarando uma variável utilizando o modelo auto-declarativo a := 20 fmt.Printf("O valor de 'a' era %dn", a) a = 30 fmt.Printf("O valor de 'a' agora é %dn", a)
  • 20.
    Lesson 2 -Variáveis // string name := "wilson" fmt.Println("Meu nome é", name) // float64 pi := 3.14 fmt.Printf("O valor de PI é %0.6fn", pi) // bool verdade := true mentira := false fmt.Println("Verdade é igual a mentira:", verdade == mentira) }
  • 21.
    Constantes # já vãorodando um: $ pushd 3-constantes
  • 22.
    Lesson 3 -Constantes - Exemplo package main import "fmt" const PI = 3.14 func main() { fmt.Println("O valor de PI é", PI) }
  • 23.
    Funções # já vãorodando um: $ pushd 4-funcoes
  • 24.
    Lesson 4 -Funções- Exemplo package main import "fmt" func add(x int, y int) int { return x + y } func main() { fmt.Println("O resultado de 10 + 20 é", add(10, 20)) }
  • 25.
  • 26.
    Lesson 4 -Funções- Exemplo Pública package main import "fmt" func Add(x int, y int) int { return x + y } func main() { fmt.Println("O resultado de 10 + 20 é", Add(10, 20)) }
  • 27.
  • 28.
    Lesson 4 -Funções- Exemplo Parâmetros continuados package main import "fmt" func Add(x, y int) int { return x + y } func main() { fmt.Println("O resultado de 10 + 20 é", Add(10, 20)) }
  • 29.
  • 30.
    Lesson 4 -Funções- Exemplo Parâmetros continuados package main import "fmt" func Add(x, y int) (int, int) { return x + y, 0 } func main() { result, other := Add(10, 20) fmt.Println("O resultado de 10 + 20 é", result) fmt.Println("O parametro extra é", other) }
  • 31.
    Structs # já vãorodando um: $ pushd 5-structs
  • 32.
    Lesson 5 -Structs - Exemplo package main import "fmt" type Person struct { Name string Age int Active bool }
  • 33.
    Lesson 5 -Structs - Exemplo func main() { p := Person{ Name: "Wilson Júnior", Age: 24, Active: true, } fmt.Println("Nome", p.Name) fmt.Println("Age", p.Age) fmt.Println("Active", p.Active) }
  • 34.
  • 35.
    Lesson 5 -Structs - Exemplo func changePerson(p *Person) { p.Age = 90 }
  • 36.
    Lesson 5 -Structs - Exemplo func main() { p := &Person{ Name: "Wilson Júnior", Age: 24, Active: true, } changePerson(p) fmt.Println("Nome", p.Name) fmt.Println("Age", p.Age) fmt.Println("Active", p.Active)
  • 37.
  • 38.
    Lesson 5 -Structs - Exemplo func main() { p := &Person{Name: "Wilson Júnior"} fmt.Println("Nome", p.Name) fmt.Println("Age", p.Age) fmt.Println("Active", p.Active) }
  • 39.
    Rodem e me montrem-mesuas percepções ...
  • 40.
    Arrays # já vãorodando um: $ pushd 6-arrays
  • 41.
    Lesson 6 -Arrays- Exemplo package main import "fmt" func main() { var mandamentos [2]string mandamentos[0] = "Amor" mandamentos[1] = "Paz" fmt.Println("Mandamentos: ", mandamentos) }
  • 42.
  • 43.
    Lesson 6 -Arrays- Exemplo package main import "fmt" func main() { mandamentos := [2]string{"Amor", "Paz"} fmt.Println("Mandamentos: ", mandamentos) }
  • 44.
    Desafio, faça um arrayde int de tamanho 3
  • 45.
    Slices # já vãorodando um: $ pushd 7-slices
  • 46.
    Lesson 6 -Slices - Exemplo package main import "fmt" func main() { linguagens := []string{"python", "ruby", "javascript"} linguagens = append(linguagens, "go") fmt.Println("Linguagens da globo.com: ", linguagens) fmt.Println("Linguagens da globo.com: ", linguagens[1:3])
  • 47.
    Lesson 6 -Slices - Exemplo for i, linguagem := range linguagens { fmt.Printf( "Linguagem na posição %d do slice, valor: %sn", i, linguagem, ) } }
  • 48.
  • 49.
    Lesson 6 -Arrays- Exemplo package main import "fmt" func main() { linguagens := make([]string, 0, 5) linguagens = append(linguagens, "go") fmt.Println("Linguagens da globo.com: ", linguagens) fmt.Println("Linguagens da globo.com: ", linguagens[1:3]) }
  • 50.
    Maps # já vãorodando um: $ pushd 8-maps
  • 51.
    Lesson 8 -Maps - Exemplo package main import "fmt" func main() { people := map[string]int{ "wilson": 25, "andre": 26, } people["junior"] = 10
  • 52.
    Lesson 8 -Maps - Exemplo for name, age := range people { fmt.Printf( "Chave %s do mapa valor: %dn", name, age, ) } delete(people, "wilson") fmt.Printf("Posição não alocada: %dn", people["wilson"]) }
  • 53.
    Desafio, altere o mapapara um mapa de inteiro para float64 Em 120 segundos
  • 54.
    Métodos # já vãorodando um: $ pushd 9-methods
  • 55.
    Lesson 9 -Métodos - Exemplo package main import "fmt" type Person struct { Name string Age int } func (p *Person) String() string { if p.Age < 18 { return fmt.Sprintf("Olá jovem %s, seja bem vindo", p.Name) } else if p.Age > 50 { return fmt.Sprintf("Olá senhor %s, seja bem vindo", p.Name) } return fmt.Sprintf("Olá %s, seja bem vindo", p.Name)
  • 56.
    Lesson 9 -Métodos - Exemplo func main() { person := Person{Name: "júnior", Age: 17} fmt.Println(person.String()) person = Person{Name: "Wilson", Age: 27} fmt.Println(person.String()) person = Person{Name: "Antônio", Age: 60} fmt.Println(person.String()) }
  • 57.
  • 58.
    Lesson 9 -Métodos - Exemplo func (p *Person) privateMethod() int { return p.Age * 4 }
  • 59.
    Desafio, crie um métodoprivado e o chame-o no exemplo
  • 60.
    Interfaces # já vãorodando um: $ pushd 10-interfaces
  • 61.
    Lesson 11 -Interfaces - Exemplo package main import "fmt" type Animal interface { Shout() string }
  • 62.
    Lesson 11 -Interfaces - Exemplo type Cow struct{} func (c *Cow) Shout() string { return "Muuu" }
  • 63.
    Lesson 11 -Interfaces - Exemplo type Dog struct{} func (d *Dog) Shout() string { return "Rau rau!" }
  • 64.
    Lesson 11 -Interfaces - Exemplo func main() { var animal Animal animal = &Cow{} callMyAnimal(animal) animal = &Dog{} callMyAnimal(animal) } func callMyAnimal(a Animal) { fmt.Println("My animal says:", a.Shout()) }
  • 65.
    Desafio, implemente um nova structpara a interface Animal
  • 66.
    Errors simples # jávão rodando um: $ pushd 11-errors
  • 67.
    Errors são umainterface type error interface { Error() string }
  • 68.
    Lesson 11 -Interfaces - Exemplo package main import ( "errors" "fmt" ) // ErrNotAllowed é chamado quando o menor tem menos de 19 anos var ErrNotAllowed = errors.New("Não permitida a entrada") func entryInParty(age int) (string, error) { if age < 18 { return "", ErrNotAllowed } return "TICKET", nil }
  • 69.
    Lesson 11 -Interfaces - Exemplo func main() { ticket, err := entryInParty(17) if err != nil { fmt.Println("Falha ao entrar na Balada: ", err) } ticket, err = entryInParty(17) if err == ErrNotAllowed { fmt.Println("Chame os pais da criança!") } fmt.Println("Ticket liberado", ticket) }
  • 70.
  • 71.
    Lesson 11 -Interfaces - Exemplo func genericFunction(v interface{}) string { switch v.(type) { case string: return "É uma string" case int: return "É um inteiro" case float64: return "É um ponto flutuante" } return "Não conheço" }
  • 72.
    Lesson 11 -Interfaces - Exemplo func main() { fmt.Println(genericFunction(10)) fmt.Println(genericFunction("wilson")) fmt.Println(genericFunction(3.14)) }
  • 73.
    Lesson 11 -Interfaces - Exemplo https://play.golang.org/p/POpt4HYOBJ
  • 74.
    Agora vocês já sabemo que é interfaces e errors
  • 75.
  • 76.
    Interfaces famosas dalinguagem package io type Reader interface { Read(p []byte) (n int, err error) }
  • 77.
    Interfaces famosas dalinguagem package io type Writer interface { Write(p []byte) (n int, err error) }
  • 78.
    Interfaces famosas dalinguagem package io type Closer interface { Close() error }
  • 79.
    Interfaces famosas dalinguagem package io type ReadCloser interface { Reader Closer }
  • 80.
    Não se preocupe!,não precisamos implementar nenhuma dessas interfaces!
  • 81.
    Interfaces famosas dalinguagem file, err := os.Open("myfile.txt") # *os.File implementa várias interfaces do pacote io
  • 82.
    E se euquiser usar a memória ?!
  • 83.
    Interfaces famosas dalinguagem buffer, err := bytes.NewBufferString("") # *bytes.Buffer também implementa muitas interfaces do pacote io
  • 84.
  • 85.
    Interfaces famosas dalinguagem func myFunction(file *os.File) { file.Read() }
  • 86.
    Sempre que derutilize interfaces, mas não abuse!
  • 87.
    Interfaces famosas dalinguagem func myFunction(r io.Reader) { r.Read() }
  • 88.
    O que issofacilita ?!
  • 89.
    Errors estruturados # já vãorodando um: $ pushd 12-errors
  • 90.
    Lesson 12 -Errors estruturados - Exemplo package main import "fmt" type MyError struct { Code int Cause string } func (e *MyError) Error() string { return fmt.Sprintf("Error %d", e.Code) }
  • 91.
    Lesson 12 -Errors estruturados - Exemplo func doSomething() error { return &MyError{ Code: 100, Cause: "Unexpected ...", } }
  • 92.
    Lesson 12 -Errors estruturados - Exemplo func main() { err := doSomething() if myError, ok := err.(*MyError); ok { fmt.Println("Code of error:", myError.Code) fmt.Println("Cause of error:", myError.Cause) } }
  • 93.
    Testes # já vãorodando um: $ pushd 13-tests
  • 94.
  • 95.
    Lesson 12 -Testes - Exemplo package main type Calculator struct{} func (*Calculator) Add(x, y int) int { return x + y } Dado um simples código testável
  • 96.
    Lesson 12 -Testes - Exemplo func Test(t *testing.T) { check.TestingT(t) } Plugando a library de test
  • 97.
    Lesson 12 -Testes - Exemplo type CalculatorSuite struct { calculator *Calculator } Construindo a suite
  • 98.
    Lesson 12 -Testes - Exemplo var _ = check.Suite(&CalculatorSuite{}) Registrando a suite
  • 99.
    Lesson 12 -Testes - Exemplo func (s *CalculatorSuite) SetUpSuite(c *check.C) { s.calculator = &Calculator{} } Definindo um before
  • 100.
    Lesson 12 -Testes - Exemplo func (s *CalculatorSuite) SetUpTest(c *check.C) { // do something before each test } Definindo um beforeEach
  • 101.
    Lesson 12 -Testes - Exemplo func (s *CalculatorSuite) TestAddSuccess(c *check.C) { result := s.calculator.Add(42, 10) c.Check(result, check.Equals, 52) } func (s *CalculatorSuite) TestAddFail(c *check.C) { result := s.calculator.Add(42, 10) c.Check(result, check.Equals, 10) } Escrevendo testes
  • 102.
    Lesson 12 -Testes - Exemplo func (s *CalculatorSuite) TearDownTest(c *check.C) { // do something after each test } Definindo um afterEach
  • 103.
    Lesson 12 -Testes - Exemplo func (s *CalculatorSuite) TearDownSuite(c *check.C) { // do something after test } Definindo um after
  • 104.
  • 105.
    Checkers check.DeepEquals c.Assert(value, check.DeepEquals,expected) check.Equals c.Assert(value, check.Equals, expected) check.HasLen c.Assert(list, check.HasLen, 5) check.Implements c.Assert(err, check.Implements, &e) check.Not c.Assert(value, check.Not(check.Equals), expected)
  • 106.
    Desafio, implemente alguma operaçãona struct Calculator e seus respectivos testes
  • 107.
    Goroutines # já vãorodando um: $ pushd 14-goroutines
  • 108.
    Como é aconcorrência em Python ou Ruby GIL
  • 109.
    O que temosem máquinas nos nossos datacenters
  • 111.
    Lesson 13 -Goroutine - Exemplo - Definindo uma function func task(name string) { for { fmt.Println("Executing task", name) time.Sleep(time.Second) } }
  • 112.
    Lesson 13 -Goroutine - Exemplo - Criando as goroutinas func main() { go task("goroutine 1") go task("goroutine 2") go task("goroutine 3") go task("goroutine 4") go task("goroutine 5") task("main") }
  • 113.
  • 114.
    E para comunicar comas goroutines ?
  • 115.
    Channels # já vãorodando um: $ pushd 15-channels
  • 116.
    Lesson 14 -Channels - Exemplo - Declarando uma função func task(name string, channel chan int) { for { value := <-channel fmt.Println("Executing task", value, "by", name) } }
  • 117.
    Lesson 14 -Channels - Exemplo - Declarando uma função func main() { channel := make(chan int) go task("goroutine 1", channel) go task("goroutine 2", channel) go task("goroutine 3", channel) go task("goroutine 4", channel) go task("goroutine 5", channel) for i := 0; i < 100; i++ { channel <- i } // wait all gorotines to finish time.Sleep(time.Second) }
  • 118.
    Wilson!, eu posso escutarvários channels ao mesmo tempo ?!
  • 119.
    Lesson 14 -Channels - Exemplo func myFunction(messages chan string, quit chan bool) { for { select { case message := <-messages: fmt.Println("message received: ", message) case <-quit: fmt.Println("closing the goroutine") return } } }
  • 120.
    Lesson 14 -Channels - Exemplo - Declarando uma função play.golang.org/p/cqhs6I1BDK
  • 121.
    Usando essa mesma estruturapodemos implementar: Timeouts!
  • 122.
    Lesson 14 -Channels - Exemplo package time func After(d Duration) <-chan Time
  • 123.
    Lesson 14 -Channels - Exemplo func myFunction(messages chan string) { for { select { case message := <-messages: fmt.Println("message received: ", message) case <-time.After(3 * time.Second): fmt.Println("Timeout! closing the goroutine") return } } }
  • 124.
    Lesson 14 -Channels - Exemplo play.golang.org/p/rewSr5stiR
  • 125.
    Mutexes # já vãorodando um: $ pushd 16-mutexes
  • 126.
    Lesson 15 -Mutexes - Exemplo type SafeMap struct { m map[string]string } func (s *SafeMap) Set(key, value string) { s.m[key] = value } func (s *SafeMap) Get(key string) string { return s.m[key] }
  • 127.
    Lesson 15 -Mutexes - Exemplo type SafeMap struct { mutex sync.Mutex m map[string]string } func (s *SafeMap) Set(key, value string) { s.mutex.Lock() defer s.mutex.Unlock() s.m[key] = value } func (s *SafeMap) Get(key string) string { s.mutex.Lock() defer s.mutex.Unlock() return s.m[key] }
  • 128.
  • 129.
  • 130.
    Lesson 15 -Mutexes - Exemplo type SafeMap struct { mutex sync.RWMutex m map[string]string } func (s *SafeMap) Set(key, value string) { s.mutex.Lock() defer s.mutex.Unlock() s.m[key] = value } func (s *SafeMap) Get(key string) string { s.mutex.RLock() defer s.mutex.RUnlock() return s.m[key] }
  • 131.
    WaitGroup # já vãorodando um: $ pushd 17-waitgroup
  • 132.
    Lesson 17 -WaitGroup - Exemplo type MultiWorker struct { wg sync.WaitGroup } func (w *MultiWorker) Run() { for i := 0; i < 100; i++ { w.wg.Add(1) go w.runJob(i) } w.wg.Wait() }
  • 133.
    Lesson 17 -WaitGroup - Exemplo func (w *MultiWorker) runJob(id int) { defer w.wg.Done() defer fmt.Printf("Job %d finishedn", id) if (id % 2) == 0 { time.Sleep(time.Second) } else { time.Sleep(2 * time.Second) } }
  • 134.
    Lesson 17 -WaitGroup - Exemplo func main() { w := &MultiWorker{} w.Run() }
  • 135.
  • 136.
  • 137.