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.5.md
+65-65
Original file line number
Diff line number
Diff line change
@@ -1,10 +1,10 @@
1
-
# Object-oriented
1
+
# Orientação a Objetos
2
2
3
-
We talked about functions and structs in the last two sections, but did you ever consider using functions as fields of a struct? In this section, I will introduce you to another form of function that has a receiver, which is called`method`.
3
+
Falamos sobre funções e estruturas nas duas últimas seções, mas você já considerou usar funções como campos de uma estrutura? Nesta seção, vou apresentá-lo a outra forma de função que possui um receptor, que é chamado`method` (método).
4
4
5
5
## method
6
6
7
-
Suppose you define a "rectangle" struct and you want to calculate its area. We'd typically use the following code to achieve this goal.
7
+
Suponha que você definiu uma estrutura "rectangle" (retângulo) e quer calcular a sua área. Geralmente, usamos o seguinte código para atingir esse objetivo.
8
8
9
9
package main
10
10
import "fmt"
@@ -23,30 +23,30 @@ Suppose you define a "rectangle" struct and you want to calculate its area. We'd
23
23
fmt.Println("Area of r1 is: ", area(r1))
24
24
fmt.Println("Area of r2 is: ", area(r2))
25
25
}
26
-
27
-
The above example can calculate a rectangle's area. We use the function called `area`, but it's not a method of the rectangle struct (like class methods in classic object-oriented languages). The function and struct are two independent things as you may notice.
28
26
29
-
It's not a problem so far. However, if you also have to calculate the area of a circle, square, pentagon, or any other kind of shape, you are going to need to add additional functions with very similar names.
27
+
O exemplo acima pode calcular a área de um retângulo. Usamos a função chamada `area`, mas ela não é um método da estrutura rectangle (como métodos de classe em linguagens orientadas a objetos clássicas). A função e a estrutura são duas coisas independentes, como você pode notar.
28
+
29
+
Isto não é um problema. Entretanto, se você também tem que calcular a área de um circulo, quadrado, pentágono ou qualquer outro tipo de forma, você vai precisar adicionar funções adicionais com nomes muito semelhantes.
Figure 2.8 Relationship between function and struct
33
+
Figure 2.8 Relacionamento entre funções e estruturas
34
+
35
+
Evidentemente, isso não é legal. Além disso, a área deve realmente ser a propriedade de um círculo ou retângulo.
34
36
35
-
Obviously that's not cool. Also, the area should really be the property of a circle or rectangle.
37
+
Por estas razões, temos o conceito de `method`. `method` é afiliado ao tipo. Ele possui a mesma sintaxe que as funções, exceto por um parâmetro adicional após a palavra-chave `func` chamada `receiver` (receptor), que é o corpo principal desse método.
36
38
37
-
For those reasons, we have the `method` concept. `method` is affiliated with type. It has the same syntax as functions do except for an additional parameter after the `func` keyword called the `receiver`, which is the main body of that method.
39
+
Usando o mesmo exemplo, `Rectangle.area()` pertence diretamente ao rectangle, em vez de ser uma função periférica. Mais especificamente, `length`, `width` e `area()` pertencem ao rectangle.
38
40
39
-
Using the same example, `Rectangle.area()` belongs directly to rectangle, instead of as a peripheral function. More specifically, `length`, `width` and `area()` all belong to rectangle.
41
+
Como Rob Pike disse.
40
42
41
-
As Rob Pike said.
43
+
"Um método é um função com um primeiro argumento implícito, chamado receptor."
42
44
43
-
"A method is a function with an implicit first argument, called a receiver."
Figure 2.9 Methods are different in different structs
93
+
Figure 2.9 Métodos são diferentes em diferentes estruturas
94
94
95
-
In the example above, the area() methods belong to both Rectangle and Circle respectively, so the receivers are Rectangle and Circle.
95
+
No exemplo acima, os métodos area() pertencem ao Rectangle e ao Circle respectivamente, então os receptores são Rectangle e Circle.
96
96
97
-
One thing that's worth noting is that the method with a dotted line means the receiver is passed by value, not by reference. The difference between them is that a method can change its receiver's values when the receiver is passed by reference, and it gets a copy of the receiver when the receiver is passed by value.
97
+
Um ponto que vale notar é que o método com a linha pontilhada significa que o receptor é passado por valor, não por referência. A diferença entre eles é que um método pode mudar os valores do seu receptor quando o receptor é passado por referência, e outro recebe uma cópia do receptor quando o receptor é passado por valor.
98
98
99
-
Can the receiver only be a struct? Of course not. Any type can be the receiver of a method. You may be confused about customized types. Struct is a special kind of customized type -there are more customized types.
99
+
O receptor só pode ser uma estrutura? Claro que não. Qualquer tipo pode ser o receptor de um método. Você pode estar confuso sobre tipos customizados. Estrutura é um tipo especial de tipo customizado -há mais tipos customizado.
100
100
101
-
Use the following format to define a customized type.
101
+
Use o seguinte formato para definir um tipo customizado.
102
102
103
103
type typeName typeLiteral
104
-
105
-
Examples of customized types:
104
+
105
+
Exemplos de tipos customizados:
106
106
107
107
type ages int
108
108
@@ -116,12 +116,12 @@ Examples of customized types:
116
116
...
117
117
"December":31,
118
118
}
119
-
120
-
I hope that you know how to use customized types now. Similar to `typedef` in C, we use `ages` to substitute `int` in the above example.
121
119
122
-
Let's get back to talking about `method`.
120
+
Espero que você saiba usar tipos customizados agora. Semelhante ao `typedef` em C, usamos `ages` para substituir `int` no exemplo acima.
121
+
122
+
Vamos voltar a falar sobre `method`.
123
123
124
-
You can use as many methods in custom types as you want.
124
+
Você pode usar quantos métodos quiser em tipos customizados.
125
125
126
126
package main
127
127
import "fmt"
@@ -141,7 +141,7 @@ You can use as many methods in custom types as you want.
141
141
color Color
142
142
}
143
143
144
-
type BoxList []Box //a slice of boxes
144
+
type BoxList []Box //uma slice de caixas
145
145
146
146
func (b Box) Volume() float64 {
147
147
return b.width * b.height * b.depth
@@ -195,36 +195,36 @@ You can use as many methods in custom types as you want.
195
195
196
196
fmt.Println("Obviously, now, the biggest one is", boxes.BiggestsColor().String())
197
197
}
198
-
199
-
We define some constants and customized types.
200
198
201
-
- Use `Color` as alias of `byte`.
202
-
- Define a struct `Box` which has fields height, width, length and color.
203
-
- Define a struct `BoxList` which has `Box` as its field.
199
+
Definimos algumas constantes e tipos customizados.
204
200
205
-
Then we defined some methods for our customized types.
201
+
- Usamos `Color` como apelido para `byte`.
202
+
- Definimos uma estrutura `Box` que tem os campos height (altura), width (largura), length (comprimento) e color (cor).
203
+
- Definimos uma estrutura `BoxList` que tem `Box` como seu campo.
206
204
207
-
- Volume() uses Box as its receiver and returns volume of Box.
208
-
- SetColor(c Color) changes Box's color.
209
-
- BiggestsColor() returns the color which has the biggest volume.
210
-
- PaintItBlack() sets color for all Box in BoxList to black.
211
-
- String() use Color as its receiver, returns the string format of color name.
205
+
Então, definimos alguns métodos para os nossos tipos customizados.
212
206
213
-
Is it much clearer when we use words to describe our requirements? We often write our requirements before we start coding.
207
+
- Volume() usa Box como seu receptor e retorna o volume de Box.
208
+
- SetColor(c Color) muda a cor de Box.
209
+
- BiggestsColor() retorna a cor que possui o maior volume.
210
+
- PaintItBlack() define as cores das Box em BoxList para preto.
211
+
- String() usa Color como seu receptor e retorna a palavra formatada do nome da cor.
214
212
215
-
### Use pointer as receiver
213
+
É muito mais claro quando usamos palavras para descrever nosso requisitos? Frequentemente escrevemos nossos requisitos antes de começar a programar.
216
214
217
-
Let's take a look at `SetColor` method. Its receiver is a pointer of Box. Yes, you can use `*Box` as a receiver. Why do we use a pointer here? Because we want to change Box's color in this method. Thus, if we don't use a pointer, it will only change the value inside a copy of Box.
215
+
### Usando ponteiro como receptor
218
216
219
-
If we see that a receiver is the first argument of a method, it's not hard to understand how it works.
217
+
Vamos dar uma olhada no método `SetColor`. Seu receptor é um ponteiro de Box. Sim, você pode usar `*Box` como um receptor. Por que usamos um ponteiro aqui? Porque queremos mudar as cores de Box neste método. Assim, se não usarmos um ponteiro, ele só mudará o valor dentro de um cópia de Box.
220
218
221
-
You might be asking why we aren't using `(*b).Color=c` instead of `b.Color=c` in the SetColor() method. Either one is OK here because Go knows how to interpret the assignment. Do you think Go is more fascinating now?
219
+
Se vemos que um receptor é o primeiro argumento de um método, não é difícil entender como ele funciona.
222
220
223
-
You may also be asking whether we should use`(&bl[i]).SetColor(BLACK)` in `PaintItBlack` because we pass a pointer to `SetColor`. Again, either one is OK because Go knows how to interpret it!
221
+
Você deve estar perguntando por que não estamos usando`(*b).Color=c` em vez de `b.Color=c` no método SetColor(). Qualquer um está OK aqui porque GO sabe como interpretar a atribuição. Você acha que Go é mais fascinante agora?
224
222
225
-
### Inheritance of method
223
+
Você também deve estar se perguntando se devemos usar `(&bl[i]).SetColor(BLACK)` em `PaintItBlack` porque passamos um ponteiro para `SetColor`. Novamente, qualquer um está OK porque Go sabe como interpretá-lo!
226
224
227
-
We learned about inheritance of fields in the last section. Similarly, we also have method inheritance in Go. If an anonymous field has methods, then the struct that contains the field will have all the methods from it as well.
225
+
### Herança do Método
226
+
227
+
Aprendemos sobre herança de campos na última seção. Similarmente, também temos herança de método em Go. Se um campo anônimo tiver métodos, então a estrutura que contém o campo terá todos os métodos dele também.
228
228
229
229
package main
230
230
import "fmt"
@@ -236,16 +236,16 @@ We learned about inheritance of fields in the last section. Similarly, we also h
236
236
}
237
237
238
238
type Student struct {
239
-
Human // anonymous field
239
+
Human // campo anônimo
240
240
school string
241
241
}
242
242
243
243
type Employee struct {
244
-
Human
244
+
Human
245
245
company string
246
246
}
247
247
248
-
// define a method in Human
248
+
// define um método em Human
249
249
func (h *Human) SayHi() {
250
250
fmt.Printf("Hi, I am %s you can call me on %s\n", h.name, h.phone)
251
251
}
@@ -258,9 +258,9 @@ We learned about inheritance of fields in the last section. Similarly, we also h
258
258
sam.SayHi()
259
259
}
260
260
261
-
### Method overload
261
+
### Sobrecarga de Método
262
262
263
-
If we want Employee to have its own method `SayHi`, we can define a method that has the same name in Employee, and it will hide`SayHi`in Human when we call it.
263
+
Se quisermos que Employee tenha seu próprio método `SayHi`, podemos definir um método com o mesmo nome em Employee, e ele irá sobrescrever`SayHi`em Human quando nós o chamarmos.
264
264
265
265
package main
266
266
import "fmt"
@@ -272,12 +272,12 @@ If we want Employee to have its own method `SayHi`, we can define a method that
272
272
}
273
273
274
274
type Student struct {
275
-
Human
275
+
Human
276
276
school string
277
277
}
278
278
279
279
type Employee struct {
280
-
Human
280
+
Human
281
281
company string
282
282
}
283
283
@@ -287,7 +287,7 @@ If we want Employee to have its own method `SayHi`, we can define a method that
287
287
288
288
func (e *Employee) SayHi() {
289
289
fmt.Printf("Hi, I am %s, I work at %s. Call me on %s\n", e.name,
290
-
e.company, e.phone) //Yes you can split into 2 lines here.
290
+
e.company, e.phone) //Sim, você pode dividir em 2 linhas aqui.
291
291
}
292
292
293
293
func main() {
@@ -297,11 +297,11 @@ If we want Employee to have its own method `SayHi`, we can define a method that
297
297
mark.SayHi()
298
298
sam.SayHi()
299
299
}
300
-
301
-
You are able to write an Object-oriented program now, and methods use rule of capital letter to decide whether public or private as well.
300
+
301
+
Você é capaz de escrever um programa Orientado a Objetos agora, e os métodos usam a regra de capital letter (letra maiúscula) para decidir se é público ou privado também.
0 commit comments