You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: pt-br/02.4.md
+52-52
Original file line number
Diff line number
Diff line change
@@ -2,60 +2,60 @@
2
2
3
3
## struct
4
4
5
-
We can define new types of containers of other properties or fields in Go just like in other programming languages. For example, we can create a type called `person`to represent a person, with fields name and age. We call this kind of type a`struct`.
5
+
Podemos definir novos tipos de contêineres de outras propriedades ou campos em Go exatamente como em outras linguagens de programação. Por exemplo, podemos criar um tipo chamado `person`com os campos name (nome) e age (idade) para representar uma pessoa. Chamamos este tipo de`struct` (estrutura).
6
6
7
7
type person struct {
8
8
name string
9
9
age int
10
10
}
11
11
12
-
Look how easy it is to define a`struct`!
12
+
Veja como é fácil definir uma`struct`!
13
13
14
-
There are two fields.
14
+
Existem dois campos.
15
15
16
-
-`name`is a`string`used to store a person's name.
17
-
-`age`is a`int`used to store a person's age.
16
+
-`name`é uma`string`usada para armazenar o nome da pessoa.
17
+
-`age`é um`int`usado para armazenar a idade da pessoa.
18
18
19
-
Let's see how to use it.
19
+
Vamos ver como utilizar isto.
20
20
21
21
type person struct {
22
22
name string
23
23
age int
24
24
}
25
25
26
-
var P person // p is person type
26
+
var P person // p é do tipo person
27
27
28
-
P.name = "Astaxie" // assign "Astaxie" to the field 'name' of p
29
-
P.age = 25 // assign 25 to field 'age' of p
30
-
fmt.Printf("The person's name is %s\n", P.name) // access field 'name' of p
28
+
P.name = "Astaxie" // atribui "Astaxie" para o campo 'name' de p
29
+
P.age = 25 // atribui 25 para o campo 'age' de p
30
+
fmt.Printf("The person's name is %s\n", P.name) // acessa o campo 'name' de p
31
31
32
-
There are three more ways to define a struct.
32
+
Existem outras três maneiras de definir uma estrutura.
33
33
34
-
-Assign initial values by order
34
+
-Atribuir os valores iniciais em ordem
35
35
36
36
P := person{"Tom", 25}
37
37
38
-
-Use the format`field:value`to initialize the struct without order
38
+
-Usar o formato`field:value`(campo:valor) para inicializar a estrutura sem ordem
39
39
40
40
P := person{age:24, name:"Bob"}
41
41
42
-
-Define an anonymous struct, then initialize it
42
+
-Definir uma estrutura anônima e então inicializar ela
43
43
44
44
P := struct{name string; age int}{"Amy",18}
45
45
46
-
Let's see a complete example.
46
+
Vejamos um exemplo completo.
47
47
48
48
package main
49
49
import "fmt"
50
50
51
-
// define a new type
51
+
// define um novo tipo
52
52
type person struct {
53
53
name string
54
54
age int
55
55
}
56
56
57
-
// compare the age of two people, then return the older person and differences of age
58
-
// struct is passed by value
57
+
// compara a idade de duas pessoas e retorna dois valores: a pessoa mais velha e a diferença de idade
58
+
// estrutura é passada por valor
59
59
func Older(p1, p2 person) (person, int) {
60
60
if p1.age>p2.age {
61
61
return p1, p1.age-p2.age
@@ -66,13 +66,13 @@ Let's see a complete example.
66
66
func main() {
67
67
var tom person
68
68
69
-
// initialization
69
+
// inicialização
70
70
tom.name, tom.age = "Tom", 18
71
71
72
-
// initialize two values by format "field:value"
72
+
// inicializa dois valores pelo formato "campo:valor"
73
73
bob := person{age:25, name:"Bob"}
74
74
75
-
// initialize two values with order
75
+
// inicializa dois valores em ordem
76
76
paul := person{"Paul", 43}
77
77
78
78
tb_Older, tb_diff := Older(tom, bob)
@@ -86,13 +86,13 @@ Let's see a complete example.
86
86
fmt.Printf("Of %s and %s, %s is older by %d years\n", bob.name, paul.name, bp_Older.name, bp_diff)
87
87
}
88
88
89
-
### embedded fields in struct
89
+
### Campos incorporados em struct
90
90
91
-
I've just introduced to you how to define a struct with field names and type. In fact, Go supports fields without names, but with types. We call these embedded fields.
91
+
Acabei de apresentar a você como definir uma estrutura com nomes de campos e tipos. Na verdade, Go suporta campos sem nomes, mas com tipos. Chamamos esses campos de campos incorporados (embedded fields).
92
92
93
-
When the embedded field is a struct, all the fields in that struct will implicitly be the fields in the struct in which it has been embdedded.
93
+
Quando um campo incorporado é uma estrutura, todos os campos desta estrutura serão implicitamente campos da estrutura onde ela foi incorporada.
94
94
95
-
Let's see one example.
95
+
Vejamos um exemplo.
96
96
97
97
package main
98
98
import "fmt"
@@ -104,43 +104,43 @@ Let's see one example.
104
104
}
105
105
106
106
type Student struct {
107
-
Human // embedded field, it means Student struct includes all fields that Human has.
107
+
Human // campo incorporado, significa que a estrutura Student inclui todos os campos que Human possui
108
108
specialty string
109
109
}
110
110
111
111
func main() {
112
-
// initialize a student
112
+
// inicializa um estudante
113
113
mark := Student{Human{"Mark", 25, 120}, "Computer Science"}
114
114
115
-
// access fields
115
+
// acessa os campos
116
116
fmt.Println("His name is ", mark.name)
117
117
fmt.Println("His age is ", mark.age)
118
118
fmt.Println("His weight is ", mark.weight)
119
119
fmt.Println("His specialty is ", mark.specialty)
120
-
// modify notes
120
+
// modifica a especialidade
121
121
mark.specialty = "AI"
122
122
fmt.Println("Mark changed his specialty")
123
123
fmt.Println("His specialty is ", mark.specialty)
124
-
// modify age
124
+
// modifica a idade
125
125
fmt.Println("Mark become old")
126
126
mark.age = 46
127
127
fmt.Println("His age is", mark.age)
128
-
// modify weight
128
+
// modifica o peso
129
129
fmt.Println("Mark is not an athlet anymore")
130
130
mark.weight += 60
131
131
fmt.Println("His weight is", mark.weight)
132
132
}
133
133
134
134

135
135
136
-
Figure 2.7 Inheritance in Student and Human
136
+
Figure 2.7 Herança em Student e Human
137
137
138
-
We see that we can access the age and name fields in Student just like we can in Human. This is how embedded fields work. It's very cool, isn't it? Hold on, there's something cooler! You can even use Student to access Human in this embedded field!
138
+
Vimos que podemos acessar os campos idade e nome de Student exatamente como podemos em Human. É assim que os campos incorporados funcionam. É muito legal, não é? Espere, tem algo mais legal! Você pode até usar o Student para acessar o Human neste campo incorporado!
139
139
140
140
mark.Human = Human{"Marcus", 55, 220}
141
141
mark.Human.age -= 1
142
142
143
-
All the types in Go can be used as embedded fields.
143
+
Todos os tipos em Go podem ser usados como campos incorporados.
144
144
145
145
package main
146
146
import "fmt"
@@ -154,61 +154,61 @@ All the types in Go can be used as embedded fields.
154
154
}
155
155
156
156
type Student struct {
157
-
Human // struct as embedded field
158
-
Skills // string slice as embedded field
159
-
int // built-in type as embedded field
157
+
Human // estrutura como campo incorporado
158
+
Skills // string slice como campo incorporado
159
+
int // tipo embutido como campo incorporado
160
160
specialty string
161
161
}
162
162
163
163
func main() {
164
-
// initialize Student Jane
164
+
// inicializa o Student Jane
165
165
jane := Student{Human:Human{"Jane", 35, 100}, specialty:"Biology"}
In the above example, we can see that all types can be embedded fields and we can use functions to operate on them.
183
181
184
-
There is one more problem however. If Human has a field called `phone` and Student has a field with same name, what should we do?
182
+
No exemplo acima, podemos ver que todos os tipos podem ser campos incorporados e podemos usar funções para operar sobre eles.
183
+
184
+
No entanto, existe mais um problema. Se Human possui um campo chamado `phone` e Student possui um campo com o mesmo nome, o que devemos fazer?
185
185
186
-
Go use a very simple way to solve it. The outer fields get upper access levels, which means when you access `student.phone`, we will get the field called phone in student, not the one in the Human struct. This feature can be simply seen as field `overload`ing.
186
+
Go usa uma maneira muito simples para resolver isto. Os campos externos obtêm níveis de acesso superiores, o que significa que quando você acessa `student.phone`, você irá obter o campo chamado phone de Student, e não aquele definido na estrutura Human. Este recurso pode ser visto simplesmente como uma sobrecarga de campo (field `overload`ing).
187
187
188
188
package main
189
189
import "fmt"
190
190
191
191
type Human struct {
192
192
name string
193
193
age int
194
-
phone string // Human has phone field
194
+
phone string // Human possui o campo phone
195
195
}
196
196
197
197
type Employee struct {
198
-
Human // embedded field Human
198
+
Human // campo incorporado Human
199
199
specialty string
200
-
phone string // phone in employee
200
+
phone string // phone em Employee
201
201
}
202
202
203
203
func main() {
204
204
Bob := Employee{Human{"Bob", 34, "777-444-XXXX"}, "Designer", "333-222"}
205
205
fmt.Println("Bob's work phone is:", Bob.phone)
206
-
// access phone field in Human
206
+
// acessa o campo phone em Human
207
207
fmt.Println("Bob's personal phone is:", Bob.Human.phone)
208
208
}
209
209
210
210
## Links
211
211
212
-
-[Directory](preface.md)
213
-
-Previous section: [Control statements and functions](02.3.md)
214
-
-Next section: [Object-oriented](02.5.md)
212
+
-[Sumário](preface.md)
213
+
-Seção anterior: [Declarações de controle e funções](02.3.md)
0 commit comments