1
- // Example code for Chapter 2.2 from "Build Web Application with Golang"
2
- // Purpose: Goes over the assignment and manipulation of basic data types .
1
+ // Código de exemplo para o Capítulo 2.2 do "Build Web Application with Golang"
2
+ // Propósito: Revisar os conceitos de atribuição e manipulação de tipos de dados básicos .
3
3
package main
4
4
5
5
import (
6
6
"errors"
7
7
"fmt"
8
8
)
9
9
10
- // constants
10
+ // constantes
11
11
const Pi = 3.1415926
12
12
13
- // booleans default to `false`
14
- var isActive bool // global variable
15
- var enabled , disabled = true , false // omit type of variables
13
+ // booleanos: padrão `false`
14
+ var isActive bool // variável global
15
+ var enabled , disabled = true , false // omite o tipo das variáveis
16
16
17
- // grouped definitions
17
+ // definições agrupadas
18
18
const (
19
19
i = 1e4
20
20
MaxThread = 10
21
21
prefix = "astaxie_"
22
22
)
23
23
24
24
var (
25
- frenchHello string // basic form to define string
26
- emptyString string = "" // define a string with empty string
25
+ frenchHello string // forma básica para definir strings
26
+ emptyString string = "" // define uma string vazia
27
27
)
28
28
29
29
func show_multiple_assignments () {
30
30
fmt .Println ("show_multiple_assignments()" )
31
31
var v1 int = 42
32
32
33
- // Define three variables with type "int", and initialize their values .
34
- // vname1 is v1, vname2 is v2, vname3 is v3
33
+ // Define três variáveis com o tipo "int" e inicializa seus valores .
34
+ // vname1 é v1, vname2 é v2, vname3 é v3
35
35
var v2 , v3 int = 2 , 3
36
36
37
- // `:=` only works in functions
38
- // `:=` is the short way of declaring variables without
39
- // specifying the type and using the keyboard `var`.
37
+ // `:=` funciona somente em funções
38
+ // `:=` é a maneira curta de declarar variáveis sem
39
+ // especificar o tipo e usando a palvra-chave `var`.
40
40
vname1 , vname2 , vname3 := v1 , v2 , v3
41
41
42
- // `_` disregards the returned value .
42
+ // `_` desconsidera o valor retornado .
43
43
_ , b := 34 , 35
44
44
45
45
fmt .Printf ("vname1 = %v, vname2 = %v, vname3 = %v\n " , vname1 , vname2 , vname3 )
@@ -48,9 +48,9 @@ func show_multiple_assignments() {
48
48
}
49
49
func show_bool () {
50
50
fmt .Println ("show_bool()" )
51
- var available bool // local variable
52
- valid := false // Shorthand assignment
53
- available = true // assign value to variable
51
+ var available bool // variável local
52
+ valid := false // declara a variável e infere o tipo booleano (declaração curta)
53
+ available = true // atribui um valor a variável
54
54
55
55
fmt .Printf ("valid = %v, !valid = %v\n " , valid , ! valid )
56
56
fmt .Printf ("available = %v\n " , available )
@@ -78,14 +78,14 @@ func show_different_types() {
78
78
}
79
79
func show_strings () {
80
80
fmt .Println ("show_strings()" )
81
- no , yes , maybe := "no" , "yes" , "maybe" // brief statement
81
+ no , yes , maybe := "no" , "yes" , "maybe" // declaração curta
82
82
japaneseHello := "Ohaiyou"
83
- frenchHello = "Bonjour" // basic form of assign values
83
+ frenchHello = "Bonjour" // forma básica de atribuir valores
84
84
85
85
fmt .Println ("Random strings" )
86
86
fmt .Println (frenchHello , japaneseHello , no , yes , maybe )
87
87
88
- // The backtick , `, will not escape any character in a string
88
+ // A crase , `, não deixa escapar qualquer caractere da string
89
89
fmt .Println (`This
90
90
is on
91
91
multiple lines` )
@@ -94,18 +94,18 @@ func show_string_manipulation() {
94
94
fmt .Println ("show_string_manipulation()" )
95
95
var s string = "hello"
96
96
97
- //You can't do this with strings
97
+ //Você não pode fazer isso com strings
98
98
//s[0] = 'c'
99
99
100
100
s = "hello"
101
- c := []byte (s ) // convert string to []byte type
101
+ c := []byte (s ) // converte string para o tipo []byte
102
102
c [0 ] = 'c'
103
- s2 := string (c ) // convert back to string type
103
+ s2 := string (c ) // converte novamente para o tipo string
104
104
105
105
m := " world"
106
106
a := s + m
107
107
108
- d := "c" + s [1 :] // you cannot change string values by index, but you can get values instead.
108
+ d := "c" + s [1 :] // você não pode alterar valores de string pelo índice, mas você pode obter os valores desta maneira
109
109
fmt .Printf ("%s\n " , d )
110
110
111
111
fmt .Printf ("s = %s, c = %v\n " , s , c )
@@ -125,66 +125,66 @@ func show_iota() {
125
125
x = iota // x == 0
126
126
y = iota // y == 1
127
127
z = iota // z == 2
128
- w // If there is no expression after constants name ,
129
- // it uses the last expression, so here is saying w = iota implicitly .
130
- // Therefore w == 3, and y and x both can omit "= iota" as well .
128
+ w // Se não houver nenhuma expressão após o nome da constante ,
129
+ // ela usa a última expressão, ou seja, neste caso w = iota implicitamente .
130
+ // Portanto w == 3, e tanto y quanto z podem omitir "= iota" também .
131
131
)
132
132
133
- const v = iota // once iota meets keyword `const`, it resets to `0`, so v = 0.
133
+ const v = iota // uma vez que iota encontra a palavra-chave `const`, ela é redefinida para `0`, então v = 0.
134
134
135
135
const (
136
- e , f , g = iota , iota , iota // e=0,f=0,g=0 values of iota are same in one line .
136
+ e , f , g = iota , iota , iota // e=0,f=0,g=0 valores de iota são iguais quando estão na mesma linha .
137
137
)
138
138
fmt .Printf ("x = %v, y = %v, z = %v, w = %v\n " , x , y , z , w )
139
139
fmt .Printf ("v = %v\n " , v )
140
140
fmt .Printf ("e = %v, f = %v, g = %v\n " , e , f , g )
141
141
}
142
142
143
- // Functions and variables starting with a capital letter are public to other packages .
144
- // Everything else is private .
143
+ // Funções e variáveis começando com uma letra maiúscula são públicas para outros pacotes .
144
+ // Todo o resto é privado .
145
145
func This_is_public () {}
146
146
func this_is_private () {}
147
147
148
148
func set_default_values () {
149
- // default values for the types .
149
+ // valores padrão para os tipos .
150
150
const (
151
151
a int = 0
152
152
b int8 = 0
153
153
c int32 = 0
154
154
d int64 = 0
155
155
e uint = 0x0
156
- f rune = 0 // the actual type of rune is int32
157
- g byte = 0x0 // the actual type of byte is uint8
158
- h float32 = 0 // length is 4 byte
159
- i float64 = 0 //length is 8 byte
156
+ f rune = 0 // o tipo real de rune é int32
157
+ g byte = 0x0 // o tipo real de byte é uint8
158
+ h float32 = 0 // comprimento é 4 bytes
159
+ i float64 = 0 // comprimento é 8 bytes
160
160
j bool = false
161
161
k string = ""
162
162
)
163
163
}
164
164
func show_arrays () {
165
165
fmt .Println ("show_arrays()" )
166
- var arr [10 ]int // an array of type int
167
- arr [0 ] = 42 // array is 0-based
168
- arr [1 ] = 13 // assign value to element
166
+ var arr [10 ]int // um array do tipo int
167
+ arr [0 ] = 42 // array é baseado em 0
168
+ arr [1 ] = 13 // atribui valor ao elemento
169
169
170
- a := [3 ]int {1 , 2 , 3 } // define a int array with 3 elements
170
+ a := [3 ]int {1 , 2 , 3 } // define um array do tipo int com 3 elementos
171
171
172
172
b := [10 ]int {1 , 2 , 3 }
173
- // define a int array with 10 elements ,
174
- // and first three are assigned, rest of them use default value 0.
173
+ // define um array do tipo int com 10 elementos ,
174
+ // e os três primeiros são atribuídos, o restante usa o valor padrão 0.
175
175
176
- c := [... ]int {4 , 5 , 6 } // use `…` replace with number of length , Go will calculate it for you .
176
+ c := [... ]int {4 , 5 , 6 } // usa `…` para substituir o número do comprimento , Go irá calcular isto para você .
177
177
178
- // define a two-dimensional array with 2 elements, and each element has 4 elements .
178
+ // define um array bidimensional com 2 elementos, e onde cada elemento possui 4 elementos .
179
179
doubleArray := [2 ][4 ]int {[4 ]int {1 , 2 , 3 , 4 }, [4 ]int {5 , 6 , 7 , 8 }}
180
180
181
- // You can write about declaration in a shorter way .
181
+ // Você pode escrever a declaração de forma curta .
182
182
easyArray := [2 ][4 ]int {{1 , 2 , 3 , 4 }, {5 , 6 , 7 , 8 }}
183
183
184
184
fmt .Println ("arr =" , arr )
185
- fmt .Printf ("The first element is %d\n " , arr [0 ]) // get element value, it returns 42
185
+ fmt .Printf ("The first element is %d\n " , arr [0 ]) // obtém o valor do elemento, retorna 42
186
186
fmt .Printf ("The last element is %d\n " , arr [9 ])
187
- //it returns default value of 10th element in this array, which is 0 in this case .
187
+ // retorna o valor padrão do décimo elemento do array, que neste caso é 0 .
188
188
189
189
fmt .Println ("array a =" , a )
190
190
fmt .Println ("array b =" , b )
@@ -195,36 +195,36 @@ func show_arrays() {
195
195
}
196
196
func show_slices () {
197
197
fmt .Println ("show_slices()" )
198
- // define a slice with 10 elements which types are byte
198
+ // define um slice de tipo byte com 10 elementos
199
199
var ar = [10 ]byte {'a' , 'b' , 'c' , 'd' , 'e' , 'f' , 'g' , 'h' , 'i' , 'j' }
200
200
201
- // define two slices with type []byte
201
+ // define dois slices com o tipo []byte
202
202
var a , b []byte
203
203
204
- // a points to elements from 3rd to 5th in array ar.
204
+ // a aponta para os elementos da posição 3 até a 5 do array ar.
205
205
a = ar [2 :5 ]
206
- // now a has elements ar[2]、 ar[3] and ar[4]
206
+ // agora a possui os elementos ar[2], ar[3] e ar[4]
207
207
208
- // b is another slice of array ar
208
+ // b é outro slice do array ar
209
209
b = ar [3 :5 ]
210
- // now b has elements ar[3] and ar[4]
210
+ // agora b possui os elementos de ar[3] e ar[4]
211
211
212
- // define an array
212
+ // define um array
213
213
var array = [10 ]byte {'a' , 'b' , 'c' , 'd' , 'e' , 'f' , 'g' , 'h' , 'i' , 'j' }
214
- // define two slices
214
+ // define dois slices
215
215
var aSlice , bSlice []byte
216
216
217
- // some convenient operations
218
- aSlice = array [:3 ] // equals to aSlice = array[0:3] aSlice has elements a,b,c
219
- aSlice = array [5 :] // equals to aSlice = array[5:10] aSlice has elements f,g,h,i,j
220
- aSlice = array [:] // equals to aSlice = array[0:10] aSlice has all elements
217
+ // algumas operações convenientes
218
+ aSlice = array [:3 ] // igual a aSlice = array[0:3] aSlice possui os elementos a,b,c
219
+ aSlice = array [5 :] // igual a aSlice = array[5:10] aSlice possui os elementos f,g,h,i,j
220
+ aSlice = array [:] // igual a aSlice = array[0:10] aSlice possui todos os elementos
221
221
222
- // slice from slice
223
- aSlice = array [3 :7 ] // aSlice has elements d,e,f,g,len=4,cap=7
224
- bSlice = aSlice [1 :3 ] // bSlice contains aSlice[1], aSlice[2], so it has elements e,f
225
- bSlice = aSlice [:3 ] // bSlice contains aSlice[0], aSlice[1], aSlice[2], so it has d,e,f
226
- bSlice = aSlice [0 :5 ] // slcie could be expanded in range of cap, now bSlice contains d,e,f,g,h
227
- bSlice = aSlice [:] // bSlice has same elements as aSlice does, which are d,e,f,g
222
+ // slice de slice
223
+ aSlice = array [3 :7 ] // aSlice possui os elementos d,e,f,g,len=4,cap=7
224
+ bSlice = aSlice [1 :3 ] // bSlice contém aSlice[1], aSlice[2], ou seja, ele possui os elementos e,f
225
+ bSlice = aSlice [:3 ] // bSlice contém aSlice[0], aSlice[1], aSlice[2], ou seja, ele possui os elementos d,e,f
226
+ bSlice = aSlice [0 :5 ] // bSlice pode ser expandido de acordo com cap, agora bSlice contém d,e,f,g,h
227
+ bSlice = aSlice [:] // bSlice possui os mesmos elementos de aSlice, os quais são d,e,f,g
228
228
229
229
fmt .Println ("slice ar =" , ar )
230
230
fmt .Println ("slice a =" , a )
@@ -236,30 +236,30 @@ func show_slices() {
236
236
}
237
237
func show_map () {
238
238
fmt .Println ("show_map()" )
239
- // use string as key type, int as value type, and you have to use `make` initialize it.
239
+ // use tipo string para a chave, tipo int para o valor, e você precisa usar `make` para inicializar
240
240
var numbers map [string ]int
241
- // another way to define map
241
+ // outra forma de declarar map
242
242
numbers = make (map [string ]int )
243
- numbers ["one" ] = 1 // assign value by key
243
+ numbers ["one" ] = 1 // atribui valor pela chave
244
244
numbers ["ten" ] = 10
245
245
numbers ["three" ] = 3
246
246
247
- // Initialize a map
247
+ // Inicializa um map
248
248
rating := map [string ]float32 {"C" : 5 , "Go" : 4.5 , "Python" : 4.5 , "C++" : 2 }
249
249
250
250
fmt .Println ("map numbers =" , numbers )
251
- fmt .Println ("The third number is: " , numbers ["three" ]) // get values
252
- // It prints : The third number is: 3
251
+ fmt .Println ("The third number is: " , numbers ["three" ]) // obtém os valores
252
+ // Isto irá imprimir : The third number is: 3
253
253
254
- // map has two return values. For second value, if the key doesn't exist,ok is false,true otherwise .
254
+ // map possui dois valores de retorno. Se a chave não existir, o segundo valor, neste caso "ok", será falso ( false). Caso contrário será verdadeiro (true) .
255
255
csharpRating , ok := rating ["C#" ]
256
256
if ok {
257
257
fmt .Println ("C# is in the map and its rating is " , csharpRating )
258
258
} else {
259
259
fmt .Println ("We have no rating associated with C# in the map" )
260
260
}
261
261
262
- delete (rating , "C" ) // delete element with key "c"
262
+ delete (rating , "C" ) // deleta o elemento com a chave "c"
263
263
fmt .Printf ("map rating = %#v\n " , rating )
264
264
}
265
265
func main () {
0 commit comments