diff --git a/examples.txt b/examples.txt index de71207..df33c16 100644 --- a/examples.txt +++ b/examples.txt @@ -74,7 +74,7 @@ Environment Variables HTTP Client HTTP Server Context -Spawning Processes -Exec'ing Processes +Spawning Processes (Invocando processos) +Executing Processes Signals Exit diff --git a/examples/arrays/arrays.go b/examples/arrays/arrays.go index 010a7e5..803a196 100644 --- a/examples/arrays/arrays.go +++ b/examples/arrays/arrays.go @@ -1,7 +1,7 @@ -// In Go, an _array_ is a numbered sequence of elements of a -// specific length. In typical Go code, [slices](slices) are -// much more common; arrays are useful in some special -// scenarios. +// Em Go, um _array_ é uma sequência numerada de elementos +// de um tamanho específico. Tipicamente, [slices](slices) são +// muito mais comuns; arrays são úteis em alguns cenários +// específicos. package main @@ -9,36 +9,35 @@ import "fmt" func main() { - // Here we create an array `a` that will hold exactly - // 5 `int`s. The type of elements and length are both - // part of the array's type. By default an array is - // zero-valued, which for `int`s means `0`s. + // Aqui é criado um array `a` com capacidade de armazenar + // exatamente 5 inteiros. O tipo de elemento que ele irá + // armazenar (int) e seu tamanho (5) são partes do tipo do array. + // Neste caso, o array tem valores padrão zero. var a [5]int - fmt.Println("emp:", a) + fmt.Println("vazio:", a) - // We can set a value at an index using the - // `array[index] = value` syntax, and get a value with - // `array[index]`. + // É possível alterar o valor de um índice do array + // utilizando a sintaxe `array[índice] = valor`, + // bem como selecionar um valor com `array[índice]`. a[4] = 100 - fmt.Println("set:", a) - fmt.Println("get:", a[4]) + fmt.Println("índice 4 alterado:", a) + fmt.Println("valor índice 4:", a[4]) - // The builtin `len` returns the length of an array. + // A função nativa `len` retorna o tamanho de um array. fmt.Println("len:", len(a)) - // Use this syntax to declare and initialize an array - // in one line. + // Para declarar a inicializar um array em uma linha, + // é possível usar esta sintaxe. b := [5]int{1, 2, 3, 4, 5} - fmt.Println("dcl:", b) + fmt.Println("array inicializado:", b) - // Array types are one-dimensional, but you can - // compose types to build multi-dimensional data - // structures. + // Arrays, via de regra são unidimensionais, mas é possível + // compor tipos para formar arrays multidimensionais. var twoD [2][3]int for i := 0; i < 2; i++ { for j := 0; j < 3; j++ { twoD[i][j] = i + j } } - fmt.Println("2d: ", twoD) + fmt.Println("bi-dimensional: ", twoD) } diff --git a/examples/arrays/arrays.hash b/examples/arrays/arrays.hash index 8e1c671..d2d6431 100644 --- a/examples/arrays/arrays.hash +++ b/examples/arrays/arrays.hash @@ -1,2 +1,2 @@ -e2bdc11af83f9c6964cfa0e06e4642943b3055ae -bBVikSoZ1Z7 +1cc84ed730687fb03976f901fe6aa6047aedf027 +6x5yvAy8AT6 diff --git a/examples/arrays/arrays.sh b/examples/arrays/arrays.sh index 76c43f6..45d6520 100644 --- a/examples/arrays/arrays.sh +++ b/examples/arrays/arrays.sh @@ -1,9 +1,9 @@ -# Note that arrays appear in the form `[v1 v2 v3 ...]` -# when printed with `fmt.Println`. +# Note que arrays aparecem na forma `[v1 v2 v3 ...]` +# quando exibidos com `fmt.Println`. $ go run arrays.go -emp: [0 0 0 0 0] -set: [0 0 0 0 100] -get: 100 +vazio: [0 0 0 0 0] +índice 4 alterado: [0 0 0 0 100] +valor índice 4: 100 len: 5 -dcl: [1 2 3 4 5] -2d: [[0 1 2] [1 2 3]] +array inicializado:: [1 2 3 4 5] +bi-dimensional: [[0 1 2] [1 2 3]] diff --git a/examples/closures/closures.go b/examples/closures/closures.go index 27def72..760ac45 100644 --- a/examples/closures/closures.go +++ b/examples/closures/closures.go @@ -1,16 +1,17 @@ -// Go supports [_anonymous functions_](https://en.wikipedia.org/wiki/Anonymous_function), -// which can form closures. -// Anonymous functions are useful when you want to define -// a function inline without having to name it. +// Go suporta [_funções anônimas_](https://en.wikipedia.org/wiki/Anonymous_function), +// as quais podem formar +// closures. +// Funções anônimas são úteis quando se pretende +// definir a função em linha sem ser necessário nomeá-la. package main import "fmt" -// This function `intSeq` returns another function, which -// we define anonymously in the body of `intSeq`. The -// returned function _closes over_ the variable `i` to -// form a closure. +// Esta função `intSeq` retorna outra função, que é +// definida anonimamente no corpo de `intSeq`. A função +// retornada _fecha sobre_ (_closes over_) a variavel +// `i` para formar um fechamento (closure). func intSeq() func() int { i := 0 return func() int { @@ -21,20 +22,20 @@ func intSeq() func() int { func main() { - // We call `intSeq`, assigning the result (a function) - // to `nextInt`. This function value captures its - // own `i` value, which will be updated each time - // we call `nextInt`. + // Aqui, a execução da função `intSeq` (que retorna outra + // função) é atribuída à variável `nextInt`. + // Esta função captura o próprio valor de `i`, que + // será atualizado a cada vez que é chamada `nextInt`. nextInt := intSeq() - // See the effect of the closure by calling `nextInt` - // a few times. + // Veja o efeito do closure chamando `nextInt` + // algumas vezes. fmt.Println(nextInt()) fmt.Println(nextInt()) fmt.Println(nextInt()) - // To confirm that the state is unique to that - // particular function, create and test a new one. + // Para confirmar que o estado é único àquela variável + // específica, ao criar outra e testar, o resultado é diverso. newInts := intSeq() fmt.Println(newInts()) } diff --git a/examples/closures/closures.hash b/examples/closures/closures.hash index 7dafe7d..2fc639a 100644 --- a/examples/closures/closures.hash +++ b/examples/closures/closures.hash @@ -1,2 +1,2 @@ -6514e124c8127250a2eecfadc9708181e51f9603 -NpgpzS8ZG8y +62c797cd5c1e484d0886b633c8af71652368ef02 +i-JqAhb-yJ1 diff --git a/examples/closures/closures.sh b/examples/closures/closures.sh index 9fc7bd8..3c08866 100644 --- a/examples/closures/closures.sh +++ b/examples/closures/closures.sh @@ -4,5 +4,5 @@ $ go run closures.go 3 1 -# The last feature of functions we'll look at for now is -# recursion. +# O último recurso de funções a ser apresentado +# é a recursão. diff --git a/examples/constants/constants.go b/examples/constants/constants.go index e7af860..8012c9b 100644 --- a/examples/constants/constants.go +++ b/examples/constants/constants.go @@ -1,5 +1,5 @@ -// Go supports _constants_ of character, string, boolean, -// and numeric values. +// Go suporta _constantes_ de tipos strings, booleanos, +// e numericos. package main @@ -8,28 +8,29 @@ import ( "math" ) -// `const` declares a constant value. +// `const` é a palavra reservada para declarar uma constante. const s string = "constant" func main() { fmt.Println(s) - // A `const` statement can appear anywhere a `var` - // statement can. + // A declaração `const` pode aparecer em qualquer + // lugar que a declaração `var` também possa. const n = 500000000 - // Constant expressions perform arithmetic with - // arbitrary precision. + // Expressões com constantes são performadas + // aritmeticamente com precisão arbitrária. const d = 3e20 / n fmt.Println(d) - // A numeric constant has no type until it's given - // one, such as by an explicit conversion. + // Uma constante numérica não possui um tipo + // até que seja atribuído um, como uma conversão explícita. fmt.Println(int64(d)) - // A number can be given a type by using it in a - // context that requires one, such as a variable - // assignment or function call. For example, here - // `math.Sin` expects a `float64`. + // Um tipo pode ser implicitamente atribuído a uma constante + // numérica ao usá-la num contexto que requer um tipo, + // como atribuição a uma variável ou uma chamada de função. + // Por exemplo, a função `math.Sin` espera um valor de tipo + // `float64`. fmt.Println(math.Sin(n)) } diff --git a/examples/constants/constants.hash b/examples/constants/constants.hash index 3f40949..1a7effc 100644 --- a/examples/constants/constants.hash +++ b/examples/constants/constants.hash @@ -1,2 +1,2 @@ -9f776516953ae57a76544444c72802d3fad63da3 -Vw-pXSfo9_b +b03b175d283759d21b5bd2bab3dd99d0d74f9ff4 +NA0z_34sqzx diff --git a/examples/for/for.go b/examples/for/for.go index 9a4df30..e3e1b05 100644 --- a/examples/for/for.go +++ b/examples/for/for.go @@ -1,5 +1,5 @@ -// `for` is Go's only looping construct. Here are -// some basic types of `for` loops. +// `for` é a única ferramenta de repetição em Go. +// Aqui estão algumas formas básicas de utilização. package main @@ -7,28 +7,28 @@ import "fmt" func main() { - // The most basic type, with a single condition. + // O tipo mais simples com apenas uma condição. i := 1 for i <= 3 { fmt.Println(i) i = i + 1 } - // A classic initial/condition/after `for` loop. + // O tipo clássico com inicial, condição + // de continuação e pós iteração. for j := 7; j <= 9; j++ { fmt.Println(j) } - // `for` without a condition will loop repeatedly - // until you `break` out of the loop or `return` from - // the enclosing function. + // `for` sem nenhuma condição será repetido indefinidamente, + // até que `break` ou `return` sejam usados para interromper. for { fmt.Println("loop") break } - // You can also `continue` to the next iteration of - // the loop. + // Também é possível utilizar o comando `continue` + // para prosseguir para a próxima iteração do loop. for n := 0; n <= 5; n++ { if n%2 == 0 { continue diff --git a/examples/for/for.hash b/examples/for/for.hash index 9473e96..468f020 100644 --- a/examples/for/for.hash +++ b/examples/for/for.hash @@ -1,2 +1,2 @@ -7af221b7da2f2b22b0b1b0a1b365afc5a56ef815 -2-4H-ArwHHS +72ef42973b9b9b78fbc266d61bf3c618e15afe67 +ilDqCUXz1gQ diff --git a/examples/for/for.sh b/examples/for/for.sh index 12785eb..5b961e4 100644 --- a/examples/for/for.sh +++ b/examples/for/for.sh @@ -10,6 +10,6 @@ loop 3 5 -# We'll see some other `for` forms later when we look at -# `range` statements, channels, and other data -# structures. +# Algumas outras formas de utilizar o `for` serão +# mencionados na declarações `range`; e em outras +# estruturas como channels. diff --git a/examples/functions/functions.go b/examples/functions/functions.go index bf3e844..745559e 100644 --- a/examples/functions/functions.go +++ b/examples/functions/functions.go @@ -1,32 +1,30 @@ -// _Functions_ are central in Go. We'll learn about -// functions with a few different examples. +// _Functions_ são centrais em Go. Serão demonstradas +// funções com alguns exemplos diferentes. package main import "fmt" -// Here's a function that takes two `int`s and returns -// their sum as an `int`. +// Aqui está uma função que recebe dois inteiros `int` e retorna a soma de ambos como outro inteiro `int`. func plus(a int, b int) int { - // Go requires explicit returns, i.e. it won't - // automatically return the value of the last - // expression. + // Go exige retornos explícitos. Por exemplo, + // não será retornado automaticamente o valor + // da última expressão return a + b } -// When you have multiple consecutive parameters of -// the same type, you may omit the type name for the -// like-typed parameters up to the final parameter that -// declares the type. +// Ao existir multiplos parâmetros consecutivos de um +// mesmo tipo, é possível omitir o tipo dos parâmetros +// até a declaração do último parâmetro daquele tipo. func plusPlus(a, b, c int) int { return a + b + c } func main() { - // Call a function just as you'd expect, with - // `name(args)`. + // Para executar uma função é utilizada a + // sintaxe `nomeDaFuncao(argumentos)`. res := plus(1, 2) fmt.Println("1+2 =", res) diff --git a/examples/functions/functions.hash b/examples/functions/functions.hash index c1efad9..8ff0955 100644 --- a/examples/functions/functions.hash +++ b/examples/functions/functions.hash @@ -1,2 +1,2 @@ -94ade6d23721234a9612c9f77431106308b84953 --o49-dQfGbK +2b0fbcad1f490acff84ac28e8f20e2f4891cfec6 +D8sGhZBD4Ai diff --git a/examples/functions/functions.sh b/examples/functions/functions.sh index cc8ff15..aac7a2b 100644 --- a/examples/functions/functions.sh +++ b/examples/functions/functions.sh @@ -2,5 +2,6 @@ $ go run functions.go 1+2 = 3 1+2+3 = 6 -# There are several other features to Go functions. One is -# multiple return values, which we'll look at next. +# Existem muitos outros recursos em Funções, +# um dos quais é chamado de Retorno de Valores +# Múltiplos que será apresentado no próximo exemplo. \ No newline at end of file diff --git a/examples/hello-world/hello-world.go b/examples/hello-world/hello-world.go index 4db5bfb..2f82d53 100644 --- a/examples/hello-world/hello-world.go +++ b/examples/hello-world/hello-world.go @@ -1,5 +1,5 @@ -// Our first program will print the classic "hello world" -// message. Here's the full source code. +// O nosso primeiro programa exibirá a mensagem "hello world". +// Aqui está o código completo. package main import "fmt" diff --git a/examples/hello-world/hello-world.hash b/examples/hello-world/hello-world.hash index 658e074..cb440b8 100644 --- a/examples/hello-world/hello-world.hash +++ b/examples/hello-world/hello-world.hash @@ -1,2 +1,2 @@ -3eb6e21f5f89b9a4bf64f267972a24211f0032e7 -NeviD0awXjt +f0d362732151b2e0e19e682d0d649e0e0d08ea66 +kj7TRRdvOse diff --git a/examples/hello-world/hello-world.sh b/examples/hello-world/hello-world.sh index 5e62132..bd1b50d 100644 --- a/examples/hello-world/hello-world.sh +++ b/examples/hello-world/hello-world.sh @@ -1,17 +1,19 @@ -# To run the program, put the code in `hello-world.go` and -# use `go run`. +# Para rodar o programa, insira o código no arquivo +# `hello-world.go` e em seguida, execute o comando +# `go run`. $ go run hello-world.go hello world -# Sometimes we'll want to build our programs into -# binaries. We can do this using `go build`. +# Por vezes é útil ter nossos programas em binário. +# É possível fazer isso por meio do comando `go build` $ go build hello-world.go $ ls hello-world hello-world.go -# We can then execute the built binary directly. +# É possível, então, executar diretamente o binário +# gerado. $ ./hello-world hello world -# Now that we can run and build basic Go programs, let's -# learn more about the language. +# Agora que conseguimos executar e gerar programas +# em Go, vamos aprender mais sobre a linguagem. diff --git a/examples/if-else/if-else.go b/examples/if-else/if-else.go index 4de7c47..e655561 100644 --- a/examples/if-else/if-else.go +++ b/examples/if-else/if-else.go @@ -1,5 +1,4 @@ -// Branching with `if` and `else` in Go is -// straight-forward. +// A condicional `if` e `else` em Go é bem direta. package main @@ -7,29 +6,30 @@ import "fmt" func main() { - // Here's a basic example. + // Aqui está um exemplo básico. if 7%2 == 0 { - fmt.Println("7 is even") + fmt.Println("7 é par") } else { - fmt.Println("7 is odd") + fmt.Println("7 é ímpar") } - // You can have an `if` statement without an else. + // Também é possível utilizar o `if` sem `else`. if 8%4 == 0 { - fmt.Println("8 is divisible by 4") + fmt.Println("8 é divisível por 4") } - // A statement can precede conditionals; any variables - // declared in this statement are available in the current - // and all subsequent branches. + // Declarações podem preceder as condições; qualquer + // variável declarada na estrutura condicional ficará + // disponível em todas as suas ramificações. if num := 9; num < 0 { - fmt.Println(num, "is negative") + fmt.Println(num, "é negativo") } else if num < 10 { - fmt.Println(num, "has 1 digit") + fmt.Println(num, "possui 1 dígito") } else { - fmt.Println(num, "has multiple digits") + fmt.Println(num, "possui múltiplos dígitos") } } -// Note that you don't need parentheses around conditions -// in Go, but that the braces are required. +// É importante lembrar que não é necessário envelopar +// condicionais com parenteses em Go, no entanto, +// as chaves {} são necessárias. diff --git a/examples/if-else/if-else.hash b/examples/if-else/if-else.hash index 37363db..da94809 100644 --- a/examples/if-else/if-else.hash +++ b/examples/if-else/if-else.hash @@ -1,2 +1,2 @@ -d6a962236fc1296684cd1ffb2d95d131ed84abde -U7xcpdutgCJ +57a5f486eec14ec74c4db2dc633b38b76fea053c +1I2JHAXgr-3 diff --git a/examples/if-else/if-else.sh b/examples/if-else/if-else.sh index 52ccc11..f33164c 100644 --- a/examples/if-else/if-else.sh +++ b/examples/if-else/if-else.sh @@ -1,8 +1,8 @@ $ go run if-else.go -7 is odd -8 is divisible by 4 -9 has 1 digit +7 é ímpar +8 é divisível por 4 +9 possui 1 dígito -# There is no [ternary if](https://en.wikipedia.org/wiki/%3F:) -# in Go, so you'll need to use a full `if` statement even -# for basic conditions. +# Não há [operador ternário](https://en.wikipedia.org/wiki/%3F:) +# em Go, então é necessário utilizar `if` +# mesmo para condições básicas. diff --git a/examples/maps/maps.go b/examples/maps/maps.go index 8a40d35..e8823b2 100644 --- a/examples/maps/maps.go +++ b/examples/maps/maps.go @@ -1,5 +1,6 @@ -// _Maps_ are Go's built-in [associative data type](https://en.wikipedia.org/wiki/Associative_array) -// (sometimes called _hashes_ or _dicts_ in other languages). +// _Maps_ é o [vetor associativo](https://pt.wikipedia.org/wiki/Vetor_associativo) +// nativo de Go. +// (também chamado de _hashes_ ou _dicts_ em outras linguagens). package main @@ -7,44 +8,46 @@ import "fmt" func main() { - // To create an empty map, use the builtin `make`: - // `make(map[key-type]val-type)`. + // Para criar um map vazio, utilize o comando nativo `make`: + // `make(map[tipoDaChave]tipoDoValor)`. m := make(map[string]int) - // Set key/value pairs using typical `name[key] = val` - // syntax. + // É possível alterar ou criar pares de chave/valor + // usando a sintaxe `nomeDoMap[chave] = valor`. m["k1"] = 7 m["k2"] = 13 - // Printing a map with e.g. `fmt.Println` will show all of - // its key/value pairs. - fmt.Println("map:", m) + // Ao imprimir um map com `fmt.Println`, por exemplo, + // serão exibidos todos os pares chave/valor. + fmt.Println("mapa:", m) - // Get a value for a key with `name[key]`. + // Para selecionar o valor de determinada chave, + // usa-se o comando `nomeDoMap[chave]`. v1 := m["k1"] - fmt.Println("v1: ", v1) + fmt.Println("valor 1: ", v1) - // The builtin `len` returns the number of key/value - // pairs when called on a map. + // O comando nativo `len`, recebendo um mapa como + // argumento, retorna o número de pares chave/valor. fmt.Println("len:", len(m)) - // The builtin `delete` removes key/value pairs from - // a map. + // O comando nativo `delete` remove um determinado + // par de chave/valor do mapa. delete(m, "k2") - fmt.Println("map:", m) + fmt.Println("mapa:", m) - // The optional second return value when getting a - // value from a map indicates if the key was present - // in the map. This can be used to disambiguate - // between missing keys and keys with zero values - // like `0` or `""`. Here we didn't need the value - // itself, so we ignored it with the _blank identifier_ - // `_`. + // Ao selecionar um determinado valor em um mapa, + // existe um segundo retorno opcional, do tipo booleano, + // que indica a presença ou ausência de um determinado + // par no map. Isto pode ser utilizado para desambiguação + // entre chaves ausentes e chaves com valor zero, como + // `0` or `""`. Onde o valor correspondente à chave não + // for necessário, é possível ignorar com um identificador + // vazio `_`. _, prs := m["k2"] - fmt.Println("prs:", prs) + fmt.Println("presença da chave:", prs) - // You can also declare and initialize a new map in - // the same line with this syntax. + // Também é possível declarar e inicializar um + // novo mapa na mesma linha com a sintaxe a seguir. n := map[string]int{"foo": 1, "bar": 2} - fmt.Println("map:", n) + fmt.Println("mapa:", n) } diff --git a/examples/maps/maps.hash b/examples/maps/maps.hash index 2c0cd81..4b9d387 100644 --- a/examples/maps/maps.hash +++ b/examples/maps/maps.hash @@ -1,2 +1,2 @@ -22d147fe9402f9ff210f12b9810811c07f4d64ca -ulCzODwCde_0 +91de19de49ffa1003c309ad4c1418e025b0c7a8f +Z1XbrBn9vsr diff --git a/examples/maps/maps.sh b/examples/maps/maps.sh index da7a841..9b8279d 100644 --- a/examples/maps/maps.sh +++ b/examples/maps/maps.sh @@ -1,9 +1,9 @@ -# Note that maps appear in the form `map[k:v k:v]` when -# printed with `fmt.Println`. +# Note que os mapas são exibidos na forma `map[k:v k:v]` +# quando impressos com `fmt.Println`. $ go run maps.go -map: map[k1:7 k2:13] -v1: 7 +mapa: map[k1:7 k2:13] +valor 1: 7 len: 2 -map: map[k1:7] -prs: false -map: map[bar:2 foo:1] +mapa: map[k1:7] +presença da chave: false +mapa: map[bar:2 foo:1] diff --git a/examples/multiple-return-values/multiple-return-values.go b/examples/multiple-return-values/multiple-return-values.go index cb541c4..0f6fc82 100644 --- a/examples/multiple-return-values/multiple-return-values.go +++ b/examples/multiple-return-values/multiple-return-values.go @@ -1,27 +1,28 @@ -// Go has built-in support for _multiple return values_. -// This feature is used often in idiomatic Go, for example -// to return both result and error values from a function. +// Go tem suporte nativo para _múltiplos valores de retorno_. +// Esse recurso é utilizado frequentemente +// em Go idiomático, por exemplo, para retornar +// valores de resultado e de erro de uma função. package main import "fmt" -// The `(int, int)` in this function signature shows that -// the function returns 2 `int`s. +// A expressão `(int, int)` na assinatura desta função +// demonstra que a função retorna dois inteiros `int`. func vals() (int, int) { return 3, 7 } func main() { - // Here we use the 2 different return values from the - // call with _multiple assignment_. + // Aqui são utilizados ambos valores retornados + // da função com _atribuição múltipla_. a, b := vals() fmt.Println(a) fmt.Println(b) - // If you only want a subset of the returned values, - // use the blank identifier `_`. + // Para utilizar apenas um dos valores retornados, + // utiliza-se o identificador vazio `_`. _, c := vals() fmt.Println(c) } diff --git a/examples/multiple-return-values/multiple-return-values.hash b/examples/multiple-return-values/multiple-return-values.hash index 4d4b705..88b18a1 100644 --- a/examples/multiple-return-values/multiple-return-values.hash +++ b/examples/multiple-return-values/multiple-return-values.hash @@ -1,2 +1,2 @@ -c6e4f5dd9c55b5d2aaeb7e939c216ec76f042501 -vZdUvLB1WbK +6789db626f3d2330a6f968a0670cc220bcafcbac +7kvvjKA16K7 diff --git a/examples/multiple-return-values/multiple-return-values.sh b/examples/multiple-return-values/multiple-return-values.sh index 0d4c599..5941c6c 100644 --- a/examples/multiple-return-values/multiple-return-values.sh +++ b/examples/multiple-return-values/multiple-return-values.sh @@ -3,5 +3,6 @@ $ go run multiple-return-values.go 7 7 -# Accepting a variable number of arguments is another nice -# feature of Go functions; we'll look at this next. +# Aceitar um número variável de argumentos é outro +# ótimo recurso de Go functions; será apresentado +# no próximo exemplo. diff --git a/examples/range/range.go b/examples/range/range.go index ec44c3f..bf81c33 100644 --- a/examples/range/range.go +++ b/examples/range/range.go @@ -1,6 +1,7 @@ -// _range_ iterates over elements in a variety of data -// structures. Let's see how to use `range` with some -// of the data structures we've already learned. +// _range_ itera sobre elementos de uma variedade +// de estrutura de dados. Aqui será demonstrado como +// utilizá-lo com algumas das estruturas de dados já +// apresentadas. package main @@ -8,43 +9,43 @@ import "fmt" func main() { - // Here we use `range` to sum the numbers in a slice. - // Arrays work like this too. + // Aqui é utilizado o `range` para somar os números + // de um slice. Funciona da mesma forma em arrays. nums := []int{2, 3, 4} sum := 0 for _, num := range nums { sum += num } - fmt.Println("sum:", sum) + fmt.Println("soma:", sum) - // `range` on arrays and slices provides both the - // index and value for each entry. Above we didn't - // need the index, so we ignored it with the - // blank identifier `_`. Sometimes we actually want - // the indexes though. + // `range` tanto em arrays quanto em slices fornece + // chave e valor; ou índice e valor para cada entrada. + // No exemplo acima não foi necessário o índice, então + // foi ignorado com identificador vazio `_`. + // Algumas vezes, entretanto, os índices serão necessários. for i, num := range nums { if num == 3 { - fmt.Println("index:", i) + fmt.Println("índice:", i) } } - // `range` on map iterates over key/value pairs. + // `range` em mapas itera sobre os pares de chave/valor. kvs := map[string]string{"a": "apple", "b": "banana"} for k, v := range kvs { fmt.Printf("%s -> %s\n", k, v) } - // `range` can also iterate over just the keys of a map. + // `range` pode iterar apenas sobre as chaves de um mapa. for k := range kvs { fmt.Println("key:", k) } - // `range` on strings iterates over Unicode code - // points. The first value is the starting byte index - // of the `rune` and the second the `rune` itself. - // See [Strings and Runes](strings-and-runes) for more - // details. - for i, c := range "go" { - fmt.Println(i, c) + // `range` em strings itera sobre pontos de código Unicode. + // O primeiro valor é o byte de índice de início da `rune`, + // e o segundo, da própria `rune`. + // Veja a seção [Strings and Runes](strings-and-runes) + // para mais detalhes. + for i, rune := range "go" { + fmt.Println(i, rune) } } diff --git a/examples/range/range.hash b/examples/range/range.hash index f2e2c7b..8e80615 100644 --- a/examples/range/range.hash +++ b/examples/range/range.hash @@ -1,2 +1,2 @@ -c8da490660d234fc420f39d9b8a4aba27f8aba46 -kRsyWNmLFLz +27e654eba4cb1f7a23c99c2a07cc83d2631821ef +0jbhU_qHfKO diff --git a/examples/range/range.sh b/examples/range/range.sh index e3f40d8..628810e 100644 --- a/examples/range/range.sh +++ b/examples/range/range.sh @@ -1,6 +1,6 @@ $ go run range.go -sum: 9 -index: 1 +soma: 9 +índice: 1 a -> apple b -> banana key: a diff --git a/examples/slices/slices.go b/examples/slices/slices.go index c9335e1..a02c3ba 100644 --- a/examples/slices/slices.go +++ b/examples/slices/slices.go @@ -1,5 +1,6 @@ -// _Slices_ are an important data type in Go, giving -// a more powerful interface to sequences than arrays. +// _Slices_ é um importante tipo de dado em Go, +// oferecendo uma interface mais completa do que +// arrays para lidar com sequências. package main @@ -7,63 +8,69 @@ import "fmt" func main() { - // Unlike arrays, slices are typed only by the - // elements they contain (not the number of elements). - // To create an empty slice with non-zero length, use - // the builtin `make`. Here we make a slice of - // `string`s of length `3` (initially zero-valued). + // Diferente de arrays, slices são tipados apenas com + // tipo dos elementos que armazenará (sem um tamanho). + // Para criar um slice vazio, com tamanho não zero, + // deve-se usar o comando nativo `make`. Aqui é feito + // um slice de `string`, com tamanho 3 + // (inicialmente com valor padrão zero). s := make([]string, 3) - fmt.Println("emp:", s) + fmt.Println("vazio:", s) - // We can set and get just like with arrays. + // Para alterar os valores de um slice e seleciná-los, + // faz-se da mesma forma que com array. s[0] = "a" s[1] = "b" s[2] = "c" - fmt.Println("set:", s) - fmt.Println("get:", s[2]) + fmt.Println("exibe slice:", s) + fmt.Println("valor índice 2:", s[2]) - // `len` returns the length of the slice as expected. + // `len` retorna o tamanho de slices, da mesma forma + // que com arrays. fmt.Println("len:", len(s)) - // In addition to these basic operations, slices - // support several more that make them richer than - // arrays. One is the builtin `append`, which - // returns a slice containing one or more new values. - // Note that we need to accept a return value from - // `append` as we may get a new slice value. + // Em adição a estas operações básicas, slices + // suportam muitas outras que as fazem mais úteis do que + // arrays. Uma delas é a função nativa `append`, que + // retorna a slice contendo um ou mais novos valores. + // Note que é preciso aceitar o valor retornado da função + // `append` para ter a slice atualizada. s = append(s, "d") s = append(s, "e", "f") - fmt.Println("apd:", s) + fmt.Println("slice com acréscimo:", s) - // Slices can also be `copy`'d. Here we create an - // empty slice `c` of the same length as `s` and copy - // into `c` from `s`. + // Slices também podem ser copiadas com `copy`. Aqui + // é criado uma slice vazia `c` do mesmo tamanho da + // slice `s`. Então, a slice `s` é copiada para `c`. c := make([]string, len(s)) copy(c, s) - fmt.Println("cpy:", c) + fmt.Println("slice copiada:", c) - // Slices support a "slice" operator with the syntax - // `slice[low:high]`. For example, this gets a slice - // of the elements `s[2]`, `s[3]`, and `s[4]`. + // Slices suportam um operador "slice" com a sintaxe + // `slice[índiceBaixo:índiceAlto]`. Por exemplo, o + // comando a seguir seleciona os elementos da slice + // de índices 2, 3 e 4; ou `s[2]`, `s[3]`, e `s[4]`. l := s[2:5] - fmt.Println("sl1:", l) + fmt.Println("slice 1:", l) - // This slices up to (but excluding) `s[5]`. + // Já este, "fatia" o slice `s` até o + // índice 5 (não incluso) ou `s[5]`. l = s[:5] - fmt.Println("sl2:", l) + fmt.Println("slice 2:", l) - // And this slices up from (and including) `s[2]`. + // E este, "fatia" o slices `s` a partir do + // índice 2 (incluso) ou `s[2]`. l = s[2:] - fmt.Println("sl3:", l) + fmt.Println("slice 3:", l) - // We can declare and initialize a variable for slice - // in a single line as well. + // Também é possível declarar e inicializar um + // slice em apenas uma linha. t := []string{"g", "h", "i"} - fmt.Println("dcl:", t) + fmt.Println("slice inicializada:", t) - // Slices can be composed into multi-dimensional data - // structures. The length of the inner slices can - // vary, unlike with multi-dimensional arrays. + // Slices podem ser compsotas em estruturas + // multi-dimensionais. O tamanho das slices internas + // pode variar, diferente de arrays multi-dimensionais. twoD := make([][]int, 3) for i := 0; i < 3; i++ { innerLen := i + 1 @@ -72,5 +79,5 @@ func main() { twoD[i][j] = i + j } } - fmt.Println("2d: ", twoD) + fmt.Println("bi-dimensional: ", twoD) } diff --git a/examples/slices/slices.hash b/examples/slices/slices.hash index e23e052..4ec3221 100644 --- a/examples/slices/slices.hash +++ b/examples/slices/slices.hash @@ -1,2 +1,2 @@ -13835b88336e031808f2f3887cd43d0b9d85cad0 -76f4Jif5Z8o +bd0d70746f218672f81c716638b594350c1fa8f1 +qAON5gPJwlP diff --git a/examples/slices/slices.sh b/examples/slices/slices.sh index f29dd36..ec3ccf8 100644 --- a/examples/slices/slices.sh +++ b/examples/slices/slices.sh @@ -1,21 +1,22 @@ -# Note that while slices are different types than arrays, -# they are rendered similarly by `fmt.Println`. +# Note que enquanto slices são tipos diferentes +# de arrays, eles são exibidos de maneira similar +# pelo comando `fmt.Println`. $ go run slices.go -emp: [ ] -set: [a b c] -get: c +vazio: [ ] +exibe slice: [a b c] +valor índice 2: c len: 3 -apd: [a b c d e f] -cpy: [a b c d e f] -sl1: [c d e] -sl2: [a b c d e] -sl3: [c d e f] -dcl: [g h i] -2d: [[0] [1 2] [2 3 4]] +slice com acréscimo: [a b c d e f] +slice copiada: [a b c d e f] +slice 1: [c d e] +slice 2: [a b c d e] +slice 3: [c d e f] +slice inicializada: [g h i] +bi-dimensional: [[0] [1 2] [2 3 4]] -# Check out this [great blog post](https://go.dev/blog/slices-intro) -# by the Go team for more details on the design and -# implementation of slices in Go. +# Veja esse [post](https://go.dev/blog/slices-intro) +# do time de Go para mais detalhes sobre o design e +# implementação de slices na linguagem. -# Now that we've seen arrays and slices we'll look at -# Go's other key builtin data structure: maps. +# Agora que vimos arrays e slices, passaremos a estudar +# outra estrutura de dados nativa de Go: maps. diff --git a/examples/switch/switch.go b/examples/switch/switch.go index 2d2ec2e..0b3872e 100644 --- a/examples/switch/switch.go +++ b/examples/switch/switch.go @@ -1,5 +1,5 @@ -// _Switch statements_ express conditionals across many -// branches. +// Declarações _Switch_ são geralmente utilizadas +// para condicionais com muitas ramificações. package main @@ -10,51 +10,51 @@ import ( func main() { - // Here's a basic `switch`. + // Aqui está um `switch` básico. i := 2 - fmt.Print("Write ", i, " as ") + fmt.Print("Imprima ", i, " como ") switch i { case 1: - fmt.Println("one") + fmt.Println("um") case 2: - fmt.Println("two") + fmt.Println("dois") case 3: - fmt.Println("three") + fmt.Println("três") } - // You can use commas to separate multiple expressions - // in the same `case` statement. We use the optional - // `default` case in this example as well. + // Vírgulas podem ser utilizadas para separar múltiplas + // expressões na mesma declaração `case`. A utilização + // de `default` é opcional. switch time.Now().Weekday() { case time.Saturday, time.Sunday: - fmt.Println("It's the weekend") + fmt.Println("É fim de semana") default: - fmt.Println("It's a weekday") + fmt.Println("É dia de semana") } - // `switch` without an expression is an alternate way - // to express if/else logic. Here we also show how the - // `case` expressions can be non-constants. + // `switch` sem nenhuma expressão é um meio alternativo + // para representar a lógica if/else. Aqui também é exibido como + // as expressões `case` podem ser não constantes. t := time.Now() switch { case t.Hour() < 12: - fmt.Println("It's before noon") + fmt.Println("É antes do meio-dia") default: - fmt.Println("It's after noon") + fmt.Println("É depois do meio-dia") } - // A type `switch` compares types instead of values. You - // can use this to discover the type of an interface - // value. In this example, the variable `t` will have the - // type corresponding to its clause. + // Um `switch` de tipos compara tipos ao invés de valores. + // É possível utilizá-lo para descobrir o valor de um tipo + // interface. Neste exemplo, a variável `t` terá o tipo + // correspondente à sua cláusula. whatAmI := func(i interface{}) { switch t := i.(type) { case bool: - fmt.Println("I'm a bool") + fmt.Println("Sou um booleano") case int: - fmt.Println("I'm an int") + fmt.Println("Sou um inteiro") default: - fmt.Printf("Don't know type %T\n", t) + fmt.Printf("Não sei o meu tipo %T\n", t) } } whatAmI(true) diff --git a/examples/switch/switch.hash b/examples/switch/switch.hash index 1bd1eaa..2df8ca0 100644 --- a/examples/switch/switch.hash +++ b/examples/switch/switch.hash @@ -1,2 +1,2 @@ -28a8909ee7963cb315f14a3be1607def1d91f3a3 -qVDqWoUQ6AI +010a84fa4d50561624f3bd635a6b15c71e096436 +Y5mGHTuumK0 diff --git a/examples/switch/switch.sh b/examples/switch/switch.sh index 42e5206..ddc90d5 100644 --- a/examples/switch/switch.sh +++ b/examples/switch/switch.sh @@ -1,7 +1,7 @@ $ go run switch.go -Write 2 as two -It's a weekday -It's after noon -I'm a bool -I'm an int -Don't know type string +Imprima 2 como dois +É fim de semana +É depois do meio-dia +Sou um booleano +Sou um inteiro +Não sei o meu tipo string \ No newline at end of file diff --git a/examples/values/values.go b/examples/values/values.go index 2d34a4b..788f2b2 100644 --- a/examples/values/values.go +++ b/examples/values/values.go @@ -1,6 +1,6 @@ -// Go has various value types including strings, -// integers, floats, booleans, etc. Here are a few -// basic examples. +// Go tem vários tipos de valores, dentre eles: +// strings, integers, floats, booleans, etc. +// Aqui estão alguns exemplos básicos. package main @@ -8,14 +8,14 @@ import "fmt" func main() { - // Strings, which can be added together with `+`. + // Strings, que podem ser concatenadas usando `+`. fmt.Println("go" + "lang") - // Integers and floats. + // Integers e floats. fmt.Println("1+1 =", 1+1) fmt.Println("7.0/3.0 =", 7.0/3.0) - // Booleans, with boolean operators as you'd expect. + // Booleans, com operadores booleanos. fmt.Println(true && false) fmt.Println(true || false) fmt.Println(!true) diff --git a/examples/values/values.hash b/examples/values/values.hash index 4c64e23..55bccc3 100644 --- a/examples/values/values.hash +++ b/examples/values/values.hash @@ -1,2 +1,2 @@ -476982956a689418d548148af5f17145de16f063 -YnVS3LZr8pk +61a4fe5de5cf99bed41f516b2dd902e4589f5b67 +76t8TCPZB4E diff --git a/examples/variables/variables.go b/examples/variables/variables.go index 5fa61d4..ea2fc62 100644 --- a/examples/variables/variables.go +++ b/examples/variables/variables.go @@ -1,6 +1,6 @@ -// In Go, _variables_ are explicitly declared and used by -// the compiler to e.g. check type-correctness of function -// calls. +// Em Go, _variáveis_ são explicitamente declaradas +// e usadas pelo compilador para, por exemplo, +// verificar validade de tipos em chamadas a funções. package main @@ -8,28 +8,31 @@ import "fmt" func main() { - // `var` declares 1 or more variables. + // `var` é uma palavra reservada que é utilizada + // para declarar variáveis. var a = "initial" fmt.Println(a) - // You can declare multiple variables at once. + // Você pode declarar mais de uma variável. var b, c int = 1, 2 fmt.Println(b, c) - // Go will infer the type of initialized variables. + // Go, na ausência de declaração de um tipo, irá inferir + // o tipo da variável inicializada. var d = true fmt.Println(d) - // Variables declared without a corresponding - // initialization are _zero-valued_. For example, the - // zero value for an `int` is `0`. + // Variáveis declaradas sem um tipo correspondente são + // inicializadas com valores padrões, ou zero (zero-value). + // Por exemplo, o valor padrão para uma variável do tipo + // `int` é `0`. var e int fmt.Println(e) - // The `:=` syntax is shorthand for declaring and - // initializing a variable, e.g. for - // `var f string = "apple"` in this case. - // This syntax is only available inside functions. + // A sintaxe `:=` é uma abreviação para declarar e + // inicializar uma variavel. Por exemplo, + // `var f string = "apple"`. + // Esta sintaxe é permitida somente dentro de funções. f := "apple" fmt.Println(f) } diff --git a/examples/variables/variables.hash b/examples/variables/variables.hash index 2665b92..1561d13 100644 --- a/examples/variables/variables.hash +++ b/examples/variables/variables.hash @@ -1,2 +1,2 @@ -9aeef52b289d7ad9b9ac79f129d4e49f956c60ef -N5rWndIliJW +4477b99ff2f7744239b716c12336a6f5d6027fac +2mFIGGGSjvo diff --git a/examples/variadic-functions/variadic-functions.go b/examples/variadic-functions/variadic-functions.go index f2c88ce..76cca1f 100644 --- a/examples/variadic-functions/variadic-functions.go +++ b/examples/variadic-functions/variadic-functions.go @@ -1,20 +1,22 @@ -// [_Variadic functions_](https://en.wikipedia.org/wiki/Variadic_function) -// can be called with any number of trailing arguments. -// For example, `fmt.Println` is a common variadic -// function. +// [_Funções variádicas_](https://en.wikipedia.org/wiki/Variadic_function) +// podem ser chamads com qualquer número de argumentos. +// Por exemplo, `fmt.Println` é uma função variádica +// comumente utilizada. package main import "fmt" -// Here's a function that will take an arbitrary number -// of `int`s as arguments. +// Aqui está uma função que aceitará um número arbitrário de +// inteiros `int`s como argumento(s). +// Atenção para o operador de espalhamento (spread operator) +// que deve preceder a declaração do tipo. func sum(nums ...int) { fmt.Print(nums, " ") total := 0 - // Within the function, the type of `nums` is - // equivalent to `[]int`. We can call `len(nums)`, - // iterate over it with `range`, etc. + // Dentro da função, o tipo `nums` é + // equivalente a `[]int`. É possível usar `len(nums)`, + // iterar utilizando `range`, etc. for _, num := range nums { total += num } @@ -23,14 +25,16 @@ func sum(nums ...int) { func main() { - // Variadic functions can be called in the usual way - // with individual arguments. + // Funções variádicas pode ser chamada de + // forma usual com argumentos individuais. sum(1, 2) sum(1, 2, 3) - // If you already have multiple args in a slice, - // apply them to a variadic function using - // `func(slice...)` like this. + // Se uma slice com multiplos argumentos estiver + // disponível, é possível passá-la como parâmetro + // para uma função variádica usando `func(slice...)`. + // Atenção que agora o operador de espalhamento deve + // suceder o nome do parâmetro. nums := []int{1, 2, 3, 4} sum(nums...) } diff --git a/examples/variadic-functions/variadic-functions.hash b/examples/variadic-functions/variadic-functions.hash index 36f5ad2..3859fc9 100644 --- a/examples/variadic-functions/variadic-functions.hash +++ b/examples/variadic-functions/variadic-functions.hash @@ -1,2 +1,2 @@ -561184169a1b4c3d4970d496b282cc81016583d6 -glNdE8aKPNq +8a6a24ec58ed49771c82e94ce0ffea66fee1294f +Tl71iwyXk-F diff --git a/examples/variadic-functions/variadic-functions.sh b/examples/variadic-functions/variadic-functions.sh index feef61e..b2b2576 100644 --- a/examples/variadic-functions/variadic-functions.sh +++ b/examples/variadic-functions/variadic-functions.sh @@ -3,5 +3,6 @@ $ go run variadic-functions.go [1 2 3] 6 [1 2 3 4] 10 -# Another key aspect of functions in Go is their ability -# to form closures, which we'll look at next. +# Outro aspecto chave de funções em Go é a +# capacidade para formar fechamentos (closures), +# que serão apresentados em seguida. diff --git a/public/404.html b/public/404.html index e9e842c..06def25 100644 --- a/public/404.html +++ b/public/404.html @@ -11,7 +11,7 @@

Sorry, we couldn't find that! Check out the home page?

diff --git a/public/arrays b/public/arrays index b333813..36803d0 100644 --- a/public/arrays +++ b/public/arrays @@ -2,7 +2,7 @@ - Go by Example: Arrays + Go Em Exemplos: Arrays diff --git a/public/atomic-counters b/public/atomic-counters index 6548101..9923e14 100644 --- a/public/atomic-counters +++ b/public/atomic-counters @@ -2,7 +2,7 @@ - Go by Example: Atomic Counters + Go Em Exemplos: Atomic Counters diff --git a/public/index.html b/public/index.html index 98549d6..40074fd 100644 --- a/public/index.html +++ b/public/index.html @@ -2,27 +2,27 @@ - Go by Example + Go Em Exemplos
-

Go by Example

+

Go Em Exemplos

- Go is an - open source programming language designed for - building simple, fast, and reliable software. - Please read the official - documentation - to learn a bit about Go code, tools packages, - and modules. + Go é uma + linguagem de programação de código aberto construída para + gerar softwares simples, rápidos e confiáveis. + Leia a + documentação oficial + para aprender mais sobre Go, suas ferramentas, pacotes + e módulos.

- Go by Example is a hands-on introduction - to Go using annotated example programs. Check out - the first example or - browse the full list below. + Go by Example é uma intrudução prática + ao Go que utiliza exemplos de programas comentados. + Confira o primeiro exemplo ou + visualize a lista completa a seguir.

diff --git a/public/interfaces b/public/interfaces index 36cef1b..c596f68 100644 --- a/public/interfaces +++ b/public/interfaces @@ -2,7 +2,7 @@ - Go by Example: Interfaces + Go Em Exemplos: Interfaces diff --git a/public/methods b/public/methods index b04b063..1655ab8 100644 --- a/public/methods +++ b/public/methods @@ -2,7 +2,7 @@ - Go by Example: Methods + Go Em Exemplos: Methods diff --git a/public/range-over-channels b/public/range-over-channels index bc4b71e..32f2e3b 100644 --- a/public/range-over-channels +++ b/public/range-over-channels @@ -2,7 +2,7 @@ - Go by Example: Range over Channels + Go Em Exemplos: Range over Channels diff --git a/public/sorting b/public/sorting index e3c3508..64e6795 100644 --- a/public/sorting +++ b/public/sorting @@ -2,7 +2,7 @@ - Go by Example: Sorting + Go Em Exemplos: Sorting diff --git a/public/temporary-files-and-directories b/public/temporary-files-and-directories index fc173a7..25bf1ab 100644 --- a/public/temporary-files-and-directories +++ b/public/temporary-files-and-directories @@ -2,7 +2,7 @@ - Go by Example: Temporary Files and Directories + Go Em Exemplos: Temporary Files and Directories