提交 5b3f6299 编写于 作者: K Kelvin S. do Prado

Translation of section 2.2 to Portuguese (PT_BR).

上级 fa21e6a1
# 2.2 Fundamentos Go
In this section, we are going to teach you how to define constants, variables with elementary types and some skills in Go programming.
Nesta seção vamos aprender como definir constantes, variáveis com tipos elementares e algumas habilidades de programação em Go.
## Define variables
## Definir variáveis
There are many forms of syntax that can be used to define variables in Go.
Existem diversas formas de sintaxe que podem ser utilizadas para definir variáveis em Go.
The keyword `var` is the basic form to define variables, notice that Go puts the variable type `after` the variable name.
A palavra-chave `var` é a forma mais básica de definir variáveis. Observe que a linguagem Go coloca o tipo da variável `depois` do nome da variável.
// define a variable with name “variableName” and type "type"
// define uma variável com o nome “variableName” e o tipo "type"
var variableName type
Define multiple variables.
Definir múltiplas variáveis.
// define three variables which types are "type"
// define três variáveis do tipo "type"
var vname1, vname2, vname3 type
Define a variable with initial value.
Definir uma variável com um valor inicial.
// define a variable with name “variableName”, type "type" and value "value"
// define uma variável com o nome “variableName”, tipo "type" e valor "value"
var variableName type = value
Define multiple variables with initial values.
Definir múltiplas variáveis com valores iniciais.
/*
Define three variables with type "type", and initialize their values.
vname1 is v1, vname2 is v2, vname3 is v3
Define três variáveis de tipo "type" e inicializa seus valores.
vname1 recebe v1, vname2 recebe v2, vname3 recebe v3
*/
var vname1, vname2, vname3 type = v1, v2, v3
Do you think that it's too tedious to define variables use the way above? Don't worry, because the Go team has also found this to be a problem. Therefore if you want to define variables with initial values, we can just omit the variable type, so the code will look like this instead:
Você acha muito tedioso definir variáveis desta maneira? Não se preocupe porque a equipe da Go também achou que isto poderia ser um problema. Portanto, se você deseja definir variáveis com valores iniciais, pode simplesmente omitir o tipo da variável. Sendo assim, o código ficará da seguinte forma:
/*
Define three variables without type "type", and initialize their values.
vname1 is v1,vname2 is v2,vname3 is v3
Define três variáveis sem o tipo "type" e inicializa seus valores.
vname1 recebe v1, vname2 recebe v2, vname3 recebe v3
*/
var vname1, vname2, vname3 = v1, v2, v3
Well, I know this is still not simple enough for you. Let's see how we fix it.
Bem, talvez isto ainda não seja simples o suficiente para você. Vamos ver como podemos melhorar.
/*
Define three variables without type "type" and without keyword "var", and initialize their values.
vname1 is v1,vname2 is v2,vname3 is v3
Define três variáveis sem o tipo "type", sem a palavra-chave "var" e inicializa seus valores.
vname1 recebe v1, vname2 recebe v2, vname3 recebe v3
*/
vname1, vname2, vname3 := v1, v2, v3
Now it looks much better. Use `:=` to replace `var` and `type`, this is called a brief statement. But wait, it has one limitation: this form can only be used inside of functions. You will get compile errors if you try to use it outside of function bodies. Therefore, we usually use `var` to define global variables and we can use this brief statement in `var()`.
Agora parece muito melhor. Use `:=` para substituir `var` e `type`. Isto é chamado de uma "declaração curta" (do inglês: brief statement). Mas espere, isto possui uma limitação: esta forma só pode ser utilizada dentro de funções. Você receberá erros de compilação se tentar utilizar isto fora do corpo de uma função. Portanto, normalmente utilizamos `var` para definir variáveis globais e podemos utilizar esta declaração curta em `var()`.
`_` (blank) is a special variable name. Any value that is given to it will be ignored. For example, we give `35` to `b`, and discard `34`.( ***This example just show you how it works. It looks useless here because we often use this symbol when we get function return values.*** )
`_` (blank) é um nome especial de variável. Qualquer valor que seja atribuído a isto será ignorado. Por exemplo, vamos atribuir o valor `35` a variável `b` e descartar o valor `34`.( ***Este exemplo apenas mostra como isto funciona. Ele parece inútil aqui porque frequentemente utilizamos este símbolo quando recebemos valores de retorno de uma função. *** )
_, b := 34, 35
If you don't use variables that you've defined in your program, the compiler will give you compilation errors. Try to compile the following code and see what happens.
Se você não utilizar variáveis que foram definidas no seu programa, o compilador irá gerar erros de compilação. Tente compilar o seguinte código e veja o que acontece.
package main
......@@ -59,43 +59,43 @@ If you don't use variables that you've defined in your program, the compiler wil
var i int
}
## Constants
## Constantes
So-called constants are the values that are determined during compile time and you cannot change them during runtime. In Go, you can use number, boolean or string as types of constants.
Constantes são os valores que são determinados durante o tempo de compilação e você não pode alterá-los durante a execução. Em Go, você pode utilizar número, booleano ou string como tipos de constantes.
Define constants as follows.
Defina as constantes da seguinte forma.
const constantName = value
// you can assign type of constants if it's necessary
// você pode atribuir o tipo da constante se for necessário
const Pi float32 = 3.1415926
More examples.
Mais exemplos.
const Pi = 3.1415926
const i = 10000
const MaxThread = 10
const prefix = "astaxie_"
## Elementary types
## Tipos elementares
### Boolean
### Booleano
In Go, we use `bool` to define a variable as boolean type, the value can only be `true` or `false`, and `false` will be the default value. ( ***You cannot convert variables' type between number and boolean!*** )
Em Go, utilizamos `bool` para definir uma variável do tipo booleano, sendo que o valor só pode ser `true` ou `false`, e o valor padrão será `false`. ( ***Você não pode converter tipos de variáveis' entre número e booleano!*** )
// sample code
var isActive bool // global variable
var enabled, disabled = true, false // omit type of variables
// código de amostra
var isActive bool // variável global
var enabled, disabled = true, false // omite o tipo das variáveis
func test() {
var available bool // local variable
valid := false // brief statement of variable
available = true // assign value to variable
var available bool // variável local
valid := false // declaração curta de variável
available = true // atribui um valor à variável
}
### Numerical types
### Tipos numéricos
Integer types include both signed and unsigned integer types. Go has `int` and `uint` at the same time, they have same length, but specific length depends on your operating system. They use 32-bit in 32-bit operating systems, and 64-bit in 64-bit operating systems. Go also has types that have specific length including `rune`, `int8`, `int16`, `int32`, `int64`, `byte`, `uint8`, `uint16`, `uint32`, `uint64`. Note that `rune` is alias of `int32` and `byte` is alias of `uint8`.
Tipos inteiros incluem tipos com sinais e sem sinais. Go possui os tipos `int` e `uint`, os quais possuem o mesmo comprimento, porém, o comprimento específico depende do sistema operacional. Eles utilizam 32 bits em sistemas operacionais 32 bits e 64 bits em sistemas operacionais de 64 bits. Go também têm tipos que possuem comprimentos específicos, incluindo `rune`, `int8`, `int16`, `int32`, `int64`, `byte`, `uint8`, `uint16`, `uint32`, `uint64`. Note que `rune` é um pseudônimo de `int32` e `byte` é um pseudônimo de `uint8`.
One important thing you should know that you cannot assign values between these types, this operation will cause compile errors.
Uma coisa importante que você deve saber é que você não pode atribuir valores entre estes tipos, esta operação irá gerar erros de compilação.
var a int8
......@@ -103,86 +103,88 @@ One important thing you should know that you cannot assign values between these
c := a + b
Although int32 has a longer length than int8, and has the same type as int, you cannot assign values between them. ( ***c will be asserted as type `int` here*** )
Embora int32 tenha um comprimento maior do que int8, e possui o mesmo tipo int, você não pode atribuir valores entre eles. ( ***neste caso, c será declarado como tipo `int`*** )
Float types have the `float32` and `float64` types and no type called `float`. The latter one is the default type if using brief statement.
Tipos float possuem os tipos `float32` e `float64` e nenhum tipo chamado `float`. O último é o tipo padrão utilizado em declarações curtas.
That's all? No! Go supports complex numbers as well. `complex128` (with a 64-bit real and 64-bit imaginary part) is the default type, if you need a smaller type, there is one called `complex64` (with a 32-bit real and 32-bit imaginary part). Its form is `RE+IMi`, where `RE` is real part and `IM` is imaginary part, the last `i` is imaginary number. There is a example of complex number.
Isto é tudo? Não! Go também suporta números complexos. `complex128` (com uma parte de 64 bits real e uma parte de 64 bits imaginária) é o tipo padrão, mas se você precisa de um tipo menor, existe um tipo chamado `complex64` (com uma parte de 32 bits real e uma parte de 32 bits imaginária).
Sua forma é `RE+IMi`, onde `RE` é a parte real e `IM` é a parte imaginária, e o último `i` é o número imaginário. Há um exemplo de número complexo.
var c complex64 = 5+5i
//output: (5+5i)
// saída: (5+5i)
fmt.Printf("Value is: %v", c)
### String
We just talked about how Go uses the UTF-8 character set. Strings are represented by double quotes `""` or backticks ``` `` ```.
Nós apenas falamos sobre como a linguagem Go utiliza o conjunto de caracteres UTF-8. As strings são representadas por aspas duplas `""` ou crases (backticks) ``` `` ```.
// sample code
var frenchHello string // basic form to define string
var emptyString string = "" // define a string with empty string
// código de amostra
var frenchHello string // forma básica de definir string
var emptyString string = "" // define uma string vazia
func test() {
no, yes, maybe := "no", "yes", "maybe" // brief statement
no, yes, maybe := "no", "yes", "maybe" // declaração curta
japaneseHello := "Ohaiou"
frenchHello = "Bonjour" // basic form of assign values
frenchHello = "Bonjour" // forma básica de atribuir valores
}
It's impossible to change string values by index. You will get errors when you compile following code.
É impossível alterar valores de string pelo índice. Você receberá erros ao compilar o seguinte código.
var s string = "hello"
s[0] = 'c'
What if I really want to change just one character in a string? Try following code.
E se eu realmente quiser alterar apenas um caractere de uma string? Tente o seguinte código.
s := "hello"
c := []byte(s) // convert string to []byte type
c := []byte(s) // converte string para o tipo []byte
c[0] = 'c'
s2 := string(c) // convert back to string type
s2 := string(c) // converte novamente para o tipo string
fmt.Printf("%s\n", s2)
You use the `+` operator to combine two strings.
Use o operador `+` para combinar duas strings.
s := "hello,"
m := " world"
a := s + m
fmt.Printf("%s\n", a)
and also.
e também.
s := "hello"
s = "c" + s[1:] // you cannot change string values by index, but you can get values instead.
s = "c" + s[1:] // você não pode alterar valores da string pelo índice, mas você pode obter os valores
fmt.Printf("%s\n", s)
What if I want to have a multiple-line string?
E se eu quiser ter uma string de múltiplas linhas?
m := `hello
world`
`` ` will not escape any characters in a string.
`` ` não irá escapar nenhum caractere da string.
### Error types
### Tipos error
Go has one `error` type for purpose of dealing with error messages. There is also a package called `errors` to handle errors.
Go possui um tipo `error` com o propósito de lidar com mensagens de erro. Há também um pacote chamado `errors` para lidar com os erros.
err := errors.New("emit macho dwarf: elf header corrupted")
if err != nil {
fmt.Print(err)
}
### Underlying data structure
### Estrutura de dados subjacente
The following picture comes from an article about [Go data structure](http://research.swtch.com/godata) in [Russ Cox Blog](http://research.swtch.com/). As you can see, Go utilizes blocks of memory to store data.
A seguinte imagem vem de um artigo sobre [estruturas de dados em Go](http://research.swtch.com/godata) do [Blog Russ Cox](http://research.swtch.com/). Como você pode ver, Go utiliza blocos de memória para armazenar dados.
![](images/2.2.basic.png?raw=true)
Figure 2.1 Go underlying data structure
Figure 2.1 Estrutura de dados subjacente em Go
## Some skills
## Algumas habilidades
### Define by group
### Definir por grupo
If you want to define multiple constants, variables or import packages, you can use the group form.
Se você deseja definir múltiplas constantes, variáveis ou importar pacotes, você pode utilizar uma forma de grupo.
Basic form.
Forma básica.
import "fmt"
import "os"
......@@ -195,7 +197,7 @@ Basic form.
var pi float32
var prefix string
Group form.
Forma de grupo.
import(
"fmt"
......@@ -214,191 +216,191 @@ Group form.
prefix string
)
Unless you assign the value of constant is `iota`, the first value of constant in the group `const()` will be `0`. If following constants don't assign values explicitly, their values will be the same as the last one. If the value of last constant is `iota`, the values of following constants which are not assigned are `iota` also.
A menos que você atribua, o valor da constante é `iota`, o primeiro valor de constante no grupo `const()` será `0`. Se as constantes seguintes não atribuirem valores explicitamente, seus valores serão iguais ao último. Se o valor da última constante é `iota`, os valores das constantes seguintes que não são atribuídas será `iota` também.
### iota enumerate
### Enumeração iota
Go has one keyword called `iota`, this keyword is to make `enum`, it begins with `0`, increased by `1`.
Go possui uma palavra-chave chamada `iota`, esta palavra-chave é utilizada para fazer `enum`, ela começa com `0` e aumenta de 1 em 1.
const(
x = iota // x == 0
y = iota // y == 1
z = iota // z == 2
w // If there is no expression after the constants name, it uses the last expression, so it's saying w = iota implicitly. Therefore w == 3, and y and x both can omit "= iota" as well.
w // se não há nenhuma expressão após o nome da constate, ele usa a última expressão, ou seja, está definindo w = iota implicitamente. Portanto, w == 3, e y e x podem omitir "= iota" também.
)
const v = iota // once iota meets keyword `const`, it resets to `0`, so v = 0.
const v = iota // uma vez que iota encontra a palavra-chave `const`, ela é redefinida para `0`, então v = 0.
const (
e, f, g = iota, iota, iota // e=0,f=0,g=0 values of iota are same in one line.
e, f, g = iota, iota, iota // e=0,f=0,g=0 valores de iota são iguais em uma linha.
)
### Some rules
### Algumas regras
The reason that Go is concise because it has some default behaviors.
A razão de Go ser concisa é porque ela possui alguns comportamentos padrão.
- Any variable that begins with a capital letter means it will be exported, private otherwise.
- The same rule applies for functions and constants, no `public` or `private` keyword exists in Go.
- Qualquer variável que começa com uma letra maiúscula significa que ela será exportada, caso contrário será privada.
- A mesma regra se aplica para funções e constantes, sendo que não existem as palavras-chave `public` ou `private` em Go.
## array, slice, map
### array
`array` is an array obviously, we define one as follows.
`array` é um array obviamente, e nós definimos ele da seguinte maneira.
var arr [n]type
in `[n]type`, `n` is the length of the array, `type` is the type of its elements. Like other languages, we use `[]` to get or set element values within arrays.
em `[n]type`, `n` é o comprimento do array, enquanto `type` é o tipo dos elementos contidos no array. Assim como em outras linguagens, nós utilizamos `[]` para obter ou definir valores de elementos no array.
var arr [10]int // an array of type [10]int
arr[0] = 42 // array is 0-based
arr[1] = 13 // assign value to element
fmt.Printf("The first element is %d\n", arr[0]) // get element value, it returns 42
fmt.Printf("The last element is %d\n", arr[9]) //it returns default value of 10th element in this array, which is 0 in this case.
var arr [10]int // um array de tipo [10]int
arr[0] = 42 // array é baseado em 0
arr[1] = 13 // atribuir um valor ao elemento
fmt.Printf("The first element is %d\n", arr[0]) // obtém o valor do elemento, irá retornar 42
fmt.Printf("The last element is %d\n", arr[9]) // retorna o valor padrão do elemento da posição 10 do array, que, neste caso, é 0.
Because length is a part of the array type, `[3]int` and `[4]int` are different types, so we cannot change the length of arrays. When you use arrays as arguments, functions get their copies instead of references! If you want to use references, you may want to use `slice`. We'll talk about later.
Como o comprimento faz parte do tipo do array, `[3]int` e `[4]int` são tipos diferentes, portanto, não podemos alterar o comprimento dos arrays. Quando você utiliza arrays como argumentos, as funções obtêm suas copias em vez de referências! Se você deseja utilizar referências, você pode utilizar `slice`. Falaremos sobre isto mais tarde.
It's possible to use `:=` when you define arrays.
É possível utilizar `:=` quando você define arrays.
a := [3]int{1, 2, 3} // define an int array with 3 elements
a := [3]int{1, 2, 3} // define um array de inteiros com 3 elementos
b := [10]int{1, 2, 3} // define a int array with 10 elements, of which the first three are assigned. The rest of them use the default value 0.
b := [10]int{1, 2, 3} // define um array de inteiros com 10 elementos, dos quais os 3 primeiros são atribuídos. O restante deles recebe o valor padrão 0.
c := [...]int{4, 5, 6} // use `…` to replace the length parameter and Go will calculate it for you.
c := [...]int{4, 5, 6} // usa `…` para substituir o parâmetro de comprimento e a Go irá calcular isto para você.
You may want to use arrays as arrays' elements. Let's see how to do this.
Você pode querer utilizar arrays como elementos de arrays'. Vamos ver como fazer isto.
// define a two-dimensional array with 2 elements, and each element has 4 elements.
// define um array bidimensional com 2 elementos, e cada elemento possui 4 elementos
doubleArray := [2][4]int{[4]int{1, 2, 3, 4}, [4]int{5, 6, 7, 8}}
// The declaration can be written more concisely as follows.
// A declaração pode ser escrita de forma mais concisa da seguinte forma.
easyArray := [2][4]int{{1, 2, 3, 4}, {5, 6, 7, 8}}
Array underlying data structure.
Array estrutura de dados subjacente.
![](images/2.2.array.png?raw=true)
Figure 2.2 Multidimensional array mapping relationship
Figure 2.2 Relação de mapeamento de array multidimensional
### slice
In many situations, the array type is not a good choice -for instance when we don't know how long the array will be when we define it. Thus, we need a "dynamic array". This is called `slice` in Go.
Em várias situações, o tipo array não é uma boa escolha -por exemplo quando não sabemos o comprimento que o array terá quando o definimos. Sendo assim, precisamos de um "array dinâmico". Isto é chamado de `slice` em Go.
`slice` is not really a `dynamic array`. It's a reference type. `slice` points to an underlying `array` whose declaration is similar to `array`, but doesn't need length.
`slice` não é realmente um `array dinâmico`. É um tipo de referência. `slice` aponta para um `array` subjacente cuja declaração é semelhante ao `array`, porém não precisa de um comprimento preestabelecido.
// just like defining an array, but this time, we exclude the length.
// definimos um slice assim como definimos um array, mas desta vez, omitimos o comprimento
var fslice []int
Then we define a `slice`, and initialize its data.
Então nós definimos um `slice` e inicializamos seus dados.
slice := []byte {'a', 'b', 'c', 'd'}
`slice` can redefine existing slices or arrays. `slice` uses `array[i:j]` to slice, where `i` is the start index and `j` is end index, but notice that `array[j]` will not be sliced since the length of the slice is `j-i`.
`slice` pode redefinir slices ou arrays existentes. `slice` usa `array[i:j]` para "cortar", onde `i` é o índice de início e `j` é o índice final, mas observe que o valor de `array[j]` não será incluído no slice, pois o comprimento da fatia é `j-i`.
// define an array with 10 elements whose types are bytes
// define um array com 10 elementos cujos tipos são bytes
var ar = [10]byte {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'}
// define two slices with type []byte
// define dois slices com o tipo []byte
var a, b []byte
// 'a' points to elements from 3rd to 5th in array ar.
// 'a' aponta para os elementos da terceira até a quinta posição do array ar
a = ar[2:5]
// now 'a' has elements ar[2],ar[3] and ar[4]
// agora 'a' possui os elementos ar[2], ar[3] e ar[4]
// 'b' is another slice of array ar
// 'b' é outro slice do array ar
b = ar[3:5]
// now 'b' has elements ar[3] and ar[4]
// agora 'b' possui os elementos ar[3] e ar[4]
Notice the differences between `slice` and `array` when you define them. We use `[…]` to let Go calculate length but use `[]` to define slice only.
Observe as diferenças entre `slice` e `array` quando você define eles. Nós utilizamos `[…]` para deixar a linguagem Go calcular o comprimento, mas utilizamos `[]` para definir um slice.
Their underlying data structure.
Sua estrutura de dados subjacente.
![](images/2.2.slice.png?raw=true)
Figure 2.3 Correspondence between slice and array
Figure 2.3 Relação enter slice e array
slice has some convenient operations.
slice possui algumas operações convenientes.
- `slice` is 0-based, `ar[:n]` equals to `ar[0:n]`
- The second index will be the length of `slice` if omitted, `ar[n:]` equals to `ar[n:len(ar)]`.
- You can use `ar[:]` to slice whole array, reasons are explained in first two statements.
- `slice` é baseado em 0, `ar[:n]` igual a `ar[0:n]`
- Se omitido, o segundo índice será o comprimento do `slice`, `ar[n:]` igual a `ar[n:len(ar)]`.
- Você pode usar `ar[:]` para "cortar" o array inteiro, as razões são explicadas nas duas primeiras declarações.
More examples pertaining to `slice`
Mais exemplos referentes a `slice`
// define an array
// define um array
var array = [10]byte{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'}
// define two slices
// define dois slices
var aSlice, bSlice []byte
// some convenient operations
aSlice = array[:3] // equals to aSlice = array[0:3] aSlice has elements a,b,c
aSlice = array[5:] // equals to aSlice = array[5:10] aSlice has elements f,g,h,i,j
aSlice = array[:] // equals to aSlice = array[0:10] aSlice has all elements
// algumas operações convenientes
aSlice = array[:3] // igual a aSlice = array[0:3] aSlice possui os elementos a,b,c
aSlice = array[5:] // igual a aSlice = array[5:10] aSlice possui os elementos f,g,h,i,j
aSlice = array[:] // igual a aSlice = array[0:10] aSlice possui todos os elementos
// slice from slice
aSlice = array[3:7] // aSlice has elements d,e,f,g,len=4,cap=7
bSlice = aSlice[1:3] // bSlice contains aSlice[1], aSlice[2], so it has elements e,f
bSlice = aSlice[:3] // bSlice contains aSlice[0], aSlice[1], aSlice[2], so it has d,e,f
bSlice = aSlice[0:5] // slice could be expanded in range of cap, now bSlice contains d,e,f,g,h
bSlice = aSlice[:] // bSlice has same elements as aSlice does, which are d,e,f,g
// slice de um slice
aSlice = array[3:7] // aSlice possui os elementos d,e,f,g,len=4,cap=7
bSlice = aSlice[1:3] // bSlice contém aSlice[1], aSlice[2], então têm os elementos e,f
bSlice = aSlice[:3] // bSlice contém aSlice[0], aSlice[1], aSlice[2], então têm os elementos d,e,f
bSlice = aSlice[0:5] // slice pode ser expandido no intervalo de cap, agora bSlice contém d,e,f,g,h
bSlice = aSlice[:] // bSlice têm os mesmos elementos do slice aSlice, os quais são d,e,f,g
`slice` is a reference type, so any changes will affect other variables pointing to the same slice or array. For instance, in the case of `aSlice` and `bSlice` above, if you change the value of an element in `aSlice`, `bSlice` will be changed as well.
`slice` é um tipo de referência, portanto, qualquer alteração irá afetar outras variáveis que apontam para o mesmo slice ou array. Por exemplo, no caso dos slices `aSlice` e `bSlice` apresentado acima, se você alterar o valor de um elemento em `aSlice`, `bSlice` também será alterado.
`slice` is like a struct by definition and it contains 3 parts.
`slice` é como uma estrutura por definição, e contém 3 partes.
- A pointer that points to where `slice` starts.
- The length of `slice`.
- Capacity, the length from start index to end index of `slice`.
- Um ponteiro que aponta para onde o `slice` inicia.
- O comprimento do `slice`.
- Capacidade, o comprimento do índice de início para o índice final do `slice`.
Array_a := [10]byte{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'}
Slice_a := Array_a[2:5]
The underlying data structure of the code above as follows.
Segue a seguir a estrutura subjacente do código acima.
![](images/2.2.slice2.png?raw=true)
Figure 2.4 Array information of slice
Figure 2.4 Informações do slice de um array
There are some built-in functions for slice.
Existem algumas funções incorporadas no slice.
- `len` gets the length of `slice`.
- `cap` gets the maximum length of `slice`
- `append` appends one or more elements to `slice`, and returns `slice` .
- `copy` copies elements from one slice to the other, and returns the number of elements that were copied.
- `len` obtém o comprimento do `slice`.
- `cap` obtém o comprimento máximo do `slice`.
- `append` acrescenta um ou mais elementos ao `slice`, e retorna um `slice`.
- `copy` copia elementos de um slice para outro e retorna o número de elementos que foram copiados.
Attention: `append` will change the array that `slice` points to, and affect other slices that point to the same array. Also, if there is not enough length for the slice (`(cap-len) == 0`), `append` returns a new array for this slice. When this happens, other slices pointing to the old array will not be affected.
Atenção: `append` irá alterar o array para onde o `slice` aponta e afetará também outros slices que apontam para o mesmo array. Além disto, se não houver comprimento suficiente para o slice (`(cap-len) == 0`), `append` retorna um novo array para o slice. Quando isto acontece, outros slices que estão apontando para o array antigo não serão afetados.
### map
`map` behaves like a dictionary in Python. Use the form `map[keyType]valueType` to define it.
`map` se comporta como um dicionário em Python. Use a forma `map[keyType]valueType` para defini-lo.
Let's see some code. The 'set' and 'get' values in `map` are similar to `slice`, however the index in `slice` can only be of type 'int' while `map` can use much more than that: for example `int`, `string`, or whatever you want. Also, they are all able to use `==` and `!=` to compare values.
Vamos ver um pouco de código. Os valores 'set' e 'get' em `map` são semelhantes ao `slice`, no entanto, o índice no `slice` só pode ser do tipo 'int' enquanto `map` pode usar muitos outros tipos, como por exemplo: `int`, `string`, ou qualquer outro que você quiser. Além disto, eles são capazes de usar `==` e `!=` para comparar valores.
// use string as the key type, int as the value type, and `make` initialize it.
// use string como o tipo chave, int como o tipo valor e `make` para inicializar.
var numbers map[string] int
// another way to define map
// outra forma de definir map
numbers := make(map[string]int)
numbers["one"] = 1 // assign value by key
numbers["one"] = 1 // atribui valor por chave
numbers["ten"] = 10
numbers["three"] = 3
fmt.Println("The third number is: ", numbers["three"]) // get values
// It prints: The third number is: 3
fmt.Println("The third number is: ", numbers["three"]) // obtém valores
// Isto imprime: The third number is: 3
Some notes when you use map.
Algumas notas sobre o uso de map.
- `map` is disorderly. Everytime you print `map` you will get different results. It's impossible to get values by `index` -you have to use `key`.
- `map` doesn't have a fixed length. It's a reference type just like `slice`.
- `len` works for `map` also. It returns how many `key`s that map has.
- It's quite easy to change the value through `map`. Simply use `numbers["one"]=11` to change the value of `key` one to `11`.
- `map` é desordenado. Toda vez que você imprime `map` você terá resultados diferentes. É impossível obter valores por `índice` -você precisa utilizar `chave`.
- `map` não tem um comprimento fixo. É um tipo de referência, assim como o `slice`.
- `len` também funciona para `map`. Isto retorna quantas `chave`s o map tem.
- É muito fácil alterar valores utilizando `map`. Basta usar `numbers["one"]=11` para alterar o valor da `chave` one para `11`.
You can use form `key:val` to initialize map's values, and `map` has built-in methods to check if the `key` exists.
Você pode usar a forma `chave:valor` para inicializar valores em um `map`, pois `map` possui métodos embutidos para verificar se a `chave` existe.
Use `delete` to delete an element in `map`.
Use `delete` para deletar um elemento em um `map`.
// Initialize a map
// Inicializa um map
rating := map[string]float32 {"C":5, "Go":4.5, "Python":4.5, "C++":2 }
// map has two return values. For the second return value, if the key doesn't exist,'ok' returns false. It returns true otherwise.
// map possui dois valores de retorno. Caso a chave não exista, o segundo valor de retorno, neste caso recebido pela variável 'ok', será falso (false). Caso contrário será verdadeiro (true).
csharpRating, ok := rating["C#"]
if ok {
fmt.Println("C# is in the map and its rating is ", csharpRating)
......@@ -406,49 +408,49 @@ Use `delete` to delete an element in `map`.
fmt.Println("We have no rating associated with C# in the map")
}
delete(rating, "C") // delete element with key "c"
delete(rating, "C") // deleta o elemento com a chave "c"
As I said above, `map` is a reference type. If two `map`s point to same underlying data, any change will affect both of them.
Como foi dito acima, `map` é um tipo de referência. Se dois `map`s apontam para o mesmo dado subjacente, qualquer alteração irá afetar ambos.
m := make(map[string]string)
m["Hello"] = "Bonjour"
m1 := m
m1["Hello"] = "Salut" // now the value of m["hello"] is Salut
m1["Hello"] = "Salut" // agora o valor de m["hello"] é Salut
### make, new
`make` does memory allocation for built-in models, such as `map`, `slice`, and `channel`, while `new` is for types' memory allocation.
`make` realiza alocação de memória para modelos internos, como `map`, `slice`, e `channel`, enquanto `new` é utilizado para alocação de memória de tipos.
`new(T)` allocates zero-value to type `T`'s memory, returns its memory address, which is the value of type `*T`. By Go's definition, it returns a pointer which points to type `T`'s zero-value.
`new(T)` aloca a memória para o valor zero do tipo `T` e retorna seu endereço de memória, que é o valor do tipo `*T`. Por definição, isto retorna um ponteiro que aponta para o valor zero de `T`.
`new` returns pointers.
`new` retorna ponteiros.
The built-in function `make(T, args)` has different purposes than `new(T)`. `make` can be used for `slice`, `map`, and `channel`, and returns a type `T` with an initial value. The reason for doing this is because the underlying data of these three types must be initialized before they point to them. For example, a `slice` contains a pointer that points to the underlying `array`, length and capacity. Before these data are initialized, `slice` is `nil`, so for `slice`, `map` and `channel`, `make` initializes their underlying data and assigns some suitable values.
A função interna `make(T, args)` possui diferentes propósitos se comparado a `new(T)`. `make` pode ser usado para `slice`, `map`, e `channel`, e retorna o tipo `T` com um valor inicial. A razão para fazer isto é porque os dados subjacentes destes três tipos devem ser inicializados antes de apontar para eles. Por exemplo, um `slice` contém um ponteiro que aponta para um `array` subjacente, comprimento e capacidade. Antes que estes dados sejam inicializados, `slice` é `nil`, então, para `slice`, `map` e `channel`, `make` inicializa seus dados subjacentes e atribui alguns valores adequados.
`make` returns non-zero values.
`make` retorna valores diferentes de zero.
The following picture shows how `new` and `make` are different.
A seguinte imagem mostra como `new` e `make` são diferentes.
![](images/2.2.makenew.png?raw=true)
Figure 2.5 Underlying memory allocation of make and new
Figure 2.5 Alocação de memória para make e new
Zero-value does not mean empty value. It's the value that variables default to in most cases. Here is a list of some zero-values.
Valor zero não significa valor vazio. Na maioria dos casos é o valor padrão das variáveis. Aqui está uma lista de alguns valores zero.
int 0
int8 0
int32 0
int64 0
uint 0x0
rune 0 // the actual type of rune is int32
byte 0x0 // the actual type of byte is uint8
float32 0 // length is 4 byte
float64 0 //length is 8 byte
rune 0 // o tipo real de rune é int32
byte 0x0 // o tipo real de byte é uint8
float32 0 // comprimento é 4 bytes
float64 0 // comprimento é 8 bytes
bool false
string ""
## Links
- [Directory](preface.md)
- Previous section: ["Hello, Go"](02.1.md)
- Next section: [Control statements and functions](02.3.md)
- [Sumário](preface.md)
- Sessão anterior: ["Hello, Go"](02.1.md)
- Próxima sessão: [Control statements and functions](02.3.md)
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册