Skip to content

Commit fcab7f9

Browse files
committed
Translation of section 2.5 to Portuguese (PT-BR)
1 parent 349b1fd commit fcab7f9

File tree

1 file changed

+65
-65
lines changed

1 file changed

+65
-65
lines changed

pt-br/02.5.md

+65-65
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
1-
# Object-oriented
1+
# Orientação a Objetos
22

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).
44

55
## method
66

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.
88

99
package main
1010
import "fmt"
@@ -23,30 +23,30 @@ Suppose you define a "rectangle" struct and you want to calculate its area. We'd
2323
fmt.Println("Area of r1 is: ", area(r1))
2424
fmt.Println("Area of r2 is: ", area(r2))
2525
}
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.
2826

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.
3030

3131
![](images/2.5.rect_func_without_receiver.png?raw=true)
3232

33-
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.
3436

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.
3638

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.
3840

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.
4042

41-
As Rob Pike said.
43+
"Um método é um função com um primeiro argumento implícito, chamado receptor."
4244

43-
"A method is a function with an implicit first argument, called a receiver."
44-
45-
Syntax of method.
45+
Sintaxe do método.
4646

4747
func (r ReceiverType) funcName(parameters) (results)
48-
49-
Let's change our example using `method` instead.
48+
49+
Vamos mudar nosso exemplo usando `method` em vez disso.
5050

5151
package main
5252
import (
@@ -81,28 +81,28 @@ Let's change our example using `method` instead.
8181
fmt.Println("Area of c1 is: ", c1.area())
8282
fmt.Println("Area of c2 is: ", c2.area())
8383
}
84-
85-
Notes for using methods.
8684

87-
- If the name of methods are the same but they don't share the same receivers, they are not the same.
88-
- Methods are able to access fields within receivers.
89-
- Use `.` to call a method in the struct, the same way fields are called.
85+
Notas para o uso de métodos.
86+
87+
- Se os nomes dos métodos são os mesmos, mas eles não compartilham os mesmos receptores, eles não são os mesmos método.
88+
- Métodos são capazes de acessar campos dentro de receptores.
89+
- Use `.` para chamar um método na estrutura, da mesma forma que os campos são chamados.
9090

9191
![](images/2.5.shapes_func_with_receiver_cp.png?raw=true)
9292

93-
Figure 2.9 Methods are different in different structs
93+
Figure 2.9 Métodos são diferentes em diferentes estruturas
9494

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.
9696

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.
9898

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.
100100

101-
Use the following format to define a customized type.
101+
Use o seguinte formato para definir um tipo customizado.
102102

103103
type typeName typeLiteral
104-
105-
Examples of customized types:
104+
105+
Exemplos de tipos customizados:
106106

107107
type ages int
108108

@@ -116,12 +116,12 @@ Examples of customized types:
116116
...
117117
"December":31,
118118
}
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.
121119

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`.
123123

124-
You can use as many methods in custom types as you want.
124+
Você pode usar quantos métodos quiser em tipos customizados.
125125

126126
package main
127127
import "fmt"
@@ -141,7 +141,7 @@ You can use as many methods in custom types as you want.
141141
color Color
142142
}
143143

144-
type BoxList []Box //a slice of boxes
144+
type BoxList []Box //uma slice de caixas
145145

146146
func (b Box) Volume() float64 {
147147
return b.width * b.height * b.depth
@@ -195,36 +195,36 @@ You can use as many methods in custom types as you want.
195195

196196
fmt.Println("Obviously, now, the biggest one is", boxes.BiggestsColor().String())
197197
}
198-
199-
We define some constants and customized types.
200198

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.
204200

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.
206204

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.
212206

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.
214212

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.
216214

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
218216

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.
220218

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.
222220

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?
224222

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!
226224

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.
228228

229229
package main
230230
import "fmt"
@@ -236,16 +236,16 @@ We learned about inheritance of fields in the last section. Similarly, we also h
236236
}
237237

238238
type Student struct {
239-
Human // anonymous field
239+
Human // campo anônimo
240240
school string
241241
}
242242

243243
type Employee struct {
244-
Human
244+
Human
245245
company string
246246
}
247247

248-
// define a method in Human
248+
// define um método em Human
249249
func (h *Human) SayHi() {
250250
fmt.Printf("Hi, I am %s you can call me on %s\n", h.name, h.phone)
251251
}
@@ -258,9 +258,9 @@ We learned about inheritance of fields in the last section. Similarly, we also h
258258
sam.SayHi()
259259
}
260260

261-
### Method overload
261+
### Sobrecarga de Método
262262

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.
264264

265265
package main
266266
import "fmt"
@@ -272,12 +272,12 @@ If we want Employee to have its own method `SayHi`, we can define a method that
272272
}
273273

274274
type Student struct {
275-
Human
275+
Human
276276
school string
277277
}
278278

279279
type Employee struct {
280-
Human
280+
Human
281281
company string
282282
}
283283

@@ -287,7 +287,7 @@ If we want Employee to have its own method `SayHi`, we can define a method that
287287

288288
func (e *Employee) SayHi() {
289289
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.
291291
}
292292

293293
func main() {
@@ -297,11 +297,11 @@ If we want Employee to have its own method `SayHi`, we can define a method that
297297
mark.SayHi()
298298
sam.SayHi()
299299
}
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.
302302

303303
## Links
304304

305-
- [Directory](preface.md)
306-
- Previous section: [struct](02.4.md)
307-
- Next section: [interface](02.6.md)
305+
- [Sumário](preface.md)
306+
- Seção Anterior: [Estrutura](02.4.md)
307+
- Próxima Seção: [Interface](02.6.md)

0 commit comments

Comments
 (0)