Translation of section 2.4 to Portuguese (PT_BR).

This commit is contained in:
Kelvin Salton do Prado
2017-01-11 11:08:11 -02:00
parent 8ac3f39825
commit fe703da08e
6 changed files with 89 additions and 89 deletions

View File

@@ -2,60 +2,60 @@
## struct ## struct
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`. 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).
type person struct { type person struct {
name string name string
age int age int
} }
Look how easy it is to define a `struct`! Veja como é fácil definir uma `struct`!
There are two fields. Existem dois campos.
- `name` is a `string` used to store a person's name. - `name` é uma `string` usada para armazenar o nome da pessoa.
- `age` is a `int` used to store a person's age. - `age` é um `int` usado para armazenar a idade da pessoa.
Let's see how to use it. Vamos ver como utilizar isto.
type person struct { type person struct {
name string name string
age int age int
} }
var P person // p is person type var P person // p é do tipo person
P.name = "Astaxie" // assign "Astaxie" to the field 'name' of p P.name = "Astaxie" // atribui "Astaxie" para o campo 'name' de p
P.age = 25 // assign 25 to field 'age' of p P.age = 25 // atribui 25 para o campo 'age' de p
fmt.Printf("The person's name is %s\n", P.name) // access field 'name' of p fmt.Printf("The person's name is %s\n", P.name) // acessa o campo 'name' de p
There are three more ways to define a struct. Existem outras três maneiras de definir uma estrutura.
- Assign initial values by order - Atribuir os valores iniciais em ordem
P := person{"Tom", 25} P := person{"Tom", 25}
- Use the format `field:value` to initialize the struct without order - Usar o formato `field:value` (campo:valor) para inicializar a estrutura sem ordem
P := person{age:24, name:"Bob"} P := person{age:24, name:"Bob"}
- Define an anonymous struct, then initialize it - Definir uma estrutura anônima e então inicializar ela
P := struct{name string; age int}{"Amy",18} P := struct{name string; age int}{"Amy",18}
Let's see a complete example. Vejamos um exemplo completo.
package main package main
import "fmt" import "fmt"
// define a new type // define um novo tipo
type person struct { type person struct {
name string name string
age int age int
} }
// compare the age of two people, then return the older person and differences of age // compara a idade de duas pessoas e retorna dois valores: a pessoa mais velha e a diferença de idade
// struct is passed by value // estrutura é passada por valor
func Older(p1, p2 person) (person, int) { func Older(p1, p2 person) (person, int) {
if p1.age>p2.age { if p1.age>p2.age {
return p1, p1.age-p2.age return p1, p1.age-p2.age
@@ -66,13 +66,13 @@ Let's see a complete example.
func main() { func main() {
var tom person var tom person
// initialization // inicialização
tom.name, tom.age = "Tom", 18 tom.name, tom.age = "Tom", 18
// initialize two values by format "field:value" // inicializa dois valores pelo formato "campo:valor"
bob := person{age:25, name:"Bob"} bob := person{age:25, name:"Bob"}
// initialize two values with order // inicializa dois valores em ordem
paul := person{"Paul", 43} paul := person{"Paul", 43}
tb_Older, tb_diff := Older(tom, bob) tb_Older, tb_diff := Older(tom, bob)
@@ -86,13 +86,13 @@ Let's see a complete example.
fmt.Printf("Of %s and %s, %s is older by %d years\n", bob.name, paul.name, bp_Older.name, bp_diff) fmt.Printf("Of %s and %s, %s is older by %d years\n", bob.name, paul.name, bp_Older.name, bp_diff)
} }
### embedded fields in struct ### Campos incorporados em struct
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. 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).
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. Quando um campo incorporado é uma estrutura, todos os campos desta estrutura serão implicitamente campos da estrutura onde ela foi incorporada.
Let's see one example. Vejamos um exemplo.
package main package main
import "fmt" import "fmt"
@@ -104,28 +104,28 @@ Let's see one example.
} }
type Student struct { type Student struct {
Human // embedded field, it means Student struct includes all fields that Human has. Human // campo incorporado, significa que a estrutura Student inclui todos os campos que Human possui
specialty string specialty string
} }
func main() { func main() {
// initialize a student // inicializa um estudante
mark := Student{Human{"Mark", 25, 120}, "Computer Science"} mark := Student{Human{"Mark", 25, 120}, "Computer Science"}
// access fields // acessa os campos
fmt.Println("His name is ", mark.name) fmt.Println("His name is ", mark.name)
fmt.Println("His age is ", mark.age) fmt.Println("His age is ", mark.age)
fmt.Println("His weight is ", mark.weight) fmt.Println("His weight is ", mark.weight)
fmt.Println("His specialty is ", mark.specialty) fmt.Println("His specialty is ", mark.specialty)
// modify notes // modifica a especialidade
mark.specialty = "AI" mark.specialty = "AI"
fmt.Println("Mark changed his specialty") fmt.Println("Mark changed his specialty")
fmt.Println("His specialty is ", mark.specialty) fmt.Println("His specialty is ", mark.specialty)
// modify age // modifica a idade
fmt.Println("Mark become old") fmt.Println("Mark become old")
mark.age = 46 mark.age = 46
fmt.Println("His age is", mark.age) fmt.Println("His age is", mark.age)
// modify weight // modifica o peso
fmt.Println("Mark is not an athlet anymore") fmt.Println("Mark is not an athlet anymore")
mark.weight += 60 mark.weight += 60
fmt.Println("His weight is", mark.weight) fmt.Println("His weight is", mark.weight)
@@ -133,14 +133,14 @@ Let's see one example.
![](images/2.4.student_struct.png?raw=true) ![](images/2.4.student_struct.png?raw=true)
Figure 2.7 Inheritance in Student and Human Figure 2.7 Herança em Student e Human
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! 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!
mark.Human = Human{"Marcus", 55, 220} mark.Human = Human{"Marcus", 55, 220}
mark.Human.age -= 1 mark.Human.age -= 1
All the types in Go can be used as embedded fields. Todos os tipos em Go podem ser usados como campos incorporados.
package main package main
import "fmt" import "fmt"
@@ -154,36 +154,36 @@ All the types in Go can be used as embedded fields.
} }
type Student struct { type Student struct {
Human // struct as embedded field Human // estrutura como campo incorporado
Skills // string slice as embedded field Skills // string slice como campo incorporado
int // built-in type as embedded field int // tipo embutido como campo incorporado
specialty string specialty string
} }
func main() { func main() {
// initialize Student Jane // inicializa o Student Jane
jane := Student{Human:Human{"Jane", 35, 100}, specialty:"Biology"} jane := Student{Human:Human{"Jane", 35, 100}, specialty:"Biology"}
// access fields // acessa os campos
fmt.Println("Her name is ", jane.name) fmt.Println("Her name is ", jane.name)
fmt.Println("Her age is ", jane.age) fmt.Println("Her age is ", jane.age)
fmt.Println("Her weight is ", jane.weight) fmt.Println("Her weight is ", jane.weight)
fmt.Println("Her specialty is ", jane.specialty) fmt.Println("Her specialty is ", jane.specialty)
// modify value of skill field // modifica o valor do campo skill
jane.Skills = []string{"anatomy"} jane.Skills = []string{"anatomy"}
fmt.Println("Her skills are ", jane.Skills) fmt.Println("Her skills are ", jane.Skills)
fmt.Println("She acquired two new ones ") fmt.Println("She acquired two new ones ")
jane.Skills = append(jane.Skills, "physics", "golang") jane.Skills = append(jane.Skills, "physics", "golang")
fmt.Println("Her skills now are ", jane.Skills) fmt.Println("Her skills now are ", jane.Skills)
// modify embedded field // modifica o campo incorporado
jane.int = 3 jane.int = 3
fmt.Println("Her preferred number is", jane.int) fmt.Println("Her preferred number is", jane.int)
} }
In the above example, we can see that all types can be embedded fields and we can use functions to operate on them. No exemplo acima, podemos ver que todos os tipos podem ser campos incorporados e podemos usar funções para operar sobre eles.
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? 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?
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. 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).
package main package main
import "fmt" import "fmt"
@@ -191,24 +191,24 @@ Go use a very simple way to solve it. The outer fields get upper access levels,
type Human struct { type Human struct {
name string name string
age int age int
phone string // Human has phone field phone string // Human possui o campo phone
} }
type Employee struct { type Employee struct {
Human // embedded field Human Human // campo incorporado Human
specialty string specialty string
phone string // phone in employee phone string // phone em Employee
} }
func main() { func main() {
Bob := Employee{Human{"Bob", 34, "777-444-XXXX"}, "Designer", "333-222"} Bob := Employee{Human{"Bob", 34, "777-444-XXXX"}, "Designer", "333-222"}
fmt.Println("Bob's work phone is:", Bob.phone) fmt.Println("Bob's work phone is:", Bob.phone)
// access phone field in Human // acessa o campo phone em Human
fmt.Println("Bob's personal phone is:", Bob.Human.phone) fmt.Println("Bob's personal phone is:", Bob.Human.phone)
} }
## Links ## Links
- [Directory](preface.md) - [Sumário](preface.md)
- Previous section: [Control statements and functions](02.3.md) - Seção anterior: [Declarações de controle e funções](02.3.md)
- Next section: [Object-oriented](02.5.md) - Próxima seção: [Orientado a Objeto](02.5.md)

View File

@@ -1,17 +1,17 @@
// Example code for Chapter 2.4 from "Build Web Application with Golang" // Código de exemplo da seção 2.4 de "Build Web Application with Golang"
// Purpose: Shows you how to pass and use structs. // Propósito: Mostrar como utilizar estruturas em Go.
package main package main
import "fmt" import "fmt"
// define a new type // define um novo tipo
type person struct { type person struct {
name string name string
age int age int
} }
// compare age of two people, return the older person and differences of age // compara a idade de duas pessoas e retorna dois valores: a pessoa mais velha e a diferença de idade
// struct is passed by value // estrutura é passada por valor
func Older(p1, p2 person) (person, int) { func Older(p1, p2 person) (person, int) {
if p1.age > p2.age { if p1.age > p2.age {
return p1, p1.age - p2.age return p1, p1.age - p2.age
@@ -22,13 +22,13 @@ func Older(p1, p2 person) (person, int) {
func main() { func main() {
var tom person var tom person
// initialization // inicialização
tom.name, tom.age = "Tom", 18 tom.name, tom.age = "Tom", 18
// initialize two values by format "field:value" // inicializa dois valores pelo formato "campo:valor"
bob := person{age: 25, name: "Bob"} bob := person{age: 25, name: "Bob"}
// initialize two values with order // inicializa dois valores em ordem
paul := person{"Paul", 43} paul := person{"Paul", 43}
tb_Older, tb_diff := Older(tom, bob) tb_Older, tb_diff := Older(tom, bob)

View File

@@ -1,5 +1,5 @@
// Example code for Chapter 2.4 from "Build Web Application with Golang" // Código de exemplo da seção 2.4 de "Build Web Application with Golang"
// Purpose: Example of embedded fields // Propósito: Exemplo de campos incorporados
package main package main
import "fmt" import "fmt"
@@ -11,28 +11,28 @@ type Human struct {
} }
type Student struct { type Student struct {
Human // anonymous field, it means Student struct includes all fields that Human has. Human // campo anônimo, significa que a estrutura Student inclui todos os campos que Human possui.
speciality string speciality string
} }
func main() { func main() {
// initialize a student // inicializa um estudante
mark := Student{Human{"Mark", 25, 120}, "Computer Science"} mark := Student{Human{"Mark", 25, 120}, "Computer Science"}
// access fields // acessa os campos
fmt.Println("His name is ", mark.name) fmt.Println("His name is ", mark.name)
fmt.Println("His age is ", mark.age) fmt.Println("His age is ", mark.age)
fmt.Println("His weight is ", mark.weight) fmt.Println("His weight is ", mark.weight)
fmt.Println("His speciality is ", mark.speciality) fmt.Println("His speciality is ", mark.speciality)
// modify notes // modifica especialidade
mark.speciality = "AI" mark.speciality = "AI"
fmt.Println("Mark changed his speciality") fmt.Println("Mark changed his speciality")
fmt.Println("His speciality is ", mark.speciality) fmt.Println("His speciality is ", mark.speciality)
// modify age // modifica idade
fmt.Println("Mark become old") fmt.Println("Mark become old")
mark.age = 46 mark.age = 46
fmt.Println("His age is", mark.age) fmt.Println("His age is", mark.age)
// modify weight // modifica peso
fmt.Println("Mark is not an athlete any more") fmt.Println("Mark is not an athlete any more")
mark.weight += 60 mark.weight += 60
fmt.Println("His weight is", mark.weight) fmt.Println("His weight is", mark.weight)

View File

@@ -1,5 +1,5 @@
// Example code for Chapter 2.4 from "Build Web Application with Golang" // Código de exemplo da seção 2.4 de "Build Web Application with Golang"
// Purpose: Another example of embedded fields // Propósito: Outro exemplo de campos incorporados
package main package main
import "fmt" import "fmt"
@@ -13,27 +13,27 @@ type Human struct {
} }
type Student struct { type Student struct {
Human // struct as embedded field Human // estrutura como campo incorporado
Skills // string slice as embedded field Skills // string slice como campo incorporado
int // built-in type as embedded field int // tipo embutido como campo incorporado
speciality string speciality string
} }
func main() { func main() {
// initialize Student Jane // inicializa Student Jane
jane := Student{Human: Human{"Jane", 35, 100}, speciality: "Biology"} jane := Student{Human: Human{"Jane", 35, 100}, speciality: "Biology"}
// access fields // acessa os campos
fmt.Println("Her name is ", jane.name) fmt.Println("Her name is ", jane.name)
fmt.Println("Her age is ", jane.age) fmt.Println("Her age is ", jane.age)
fmt.Println("Her weight is ", jane.weight) fmt.Println("Her weight is ", jane.weight)
fmt.Println("Her speciality is ", jane.speciality) fmt.Println("Her speciality is ", jane.speciality)
// modify value of skill field // modifica o valor do campo skill
jane.Skills = []string{"anatomy"} jane.Skills = []string{"anatomy"}
fmt.Println("Her skills are ", jane.Skills) fmt.Println("Her skills are ", jane.Skills)
fmt.Println("She acquired two new ones ") fmt.Println("She acquired two new ones ")
jane.Skills = append(jane.Skills, "physics", "golang") jane.Skills = append(jane.Skills, "physics", "golang")
fmt.Println("Her skills now are ", jane.Skills) fmt.Println("Her skills now are ", jane.Skills)
// modify embedded field // modifica campo incorporado
jane.int = 3 jane.int = 3
fmt.Println("Her preferred number is", jane.int) fmt.Println("Her preferred number is", jane.int)
} }

View File

@@ -1,5 +1,5 @@
// Example code for Chapter 2.4 from "Build Web Application with Golang" // Código de exemplo da seção 2.4 de "Build Web Application with Golang"
// Purpose: Shows a name conflict with a embedded field // Propósito: Mostra um conflito de nomes com um campo incorporado
package main package main
import "fmt" import "fmt"
@@ -7,18 +7,18 @@ import "fmt"
type Human struct { type Human struct {
name string name string
age int age int
phone string // Human has phone field phone string // Human possui campo phone
} }
type Employee struct { type Employee struct {
Human // embedded field Human Human // campo incorporado de Human
speciality string speciality string
phone string // phone in employee phone string // phone em employee
} }
func main() { func main() {
Bob := Employee{Human{"Bob", 34, "777-444-XXXX"}, "Designer", "333-222"} Bob := Employee{Human{"Bob", 34, "777-444-XXXX"}, "Designer", "333-222"}
fmt.Println("Bob's work phone is:", Bob.phone) fmt.Println("Bob's work phone is:", Bob.phone)
// access phone field in Human // acessa o campo phone em Human
fmt.Println("Bob's personal phone is:", Bob.Human.phone) fmt.Println("Bob's personal phone is:", Bob.Human.phone)
} }

View File

@@ -1,5 +1,5 @@
// Example code for Chapter 2.4 from "Build Web Application with Golang" // Código de exemplo da seção 2.4 de "Build Web Application with Golang"
// Purpose: Shows different ways of creating a struct // Propósito: Mostrar formas diferentes de criar uma estrutura
package main package main
import "fmt" import "fmt"
@@ -11,11 +11,11 @@ func show_basic_struct() {
age int age int
} }
var P person // p is person type var P person // p é do tipo person
P.name = "Astaxie" // assign "Astaxie" to the filed 'name' of p P.name = "Astaxie" // atribui "Astaxie" ao campo 'name' de p
P.age = 25 // assign 25 to field 'age' of p P.age = 25 // atribui 25 ao campo 'age' de p
fmt.Printf("The person's name is %s\n", P.name) // access field 'name' of p fmt.Printf("The person's name is %s\n", P.name) // acessa o campo 'name' de p
tom := person{"Tom", 25} tom := person{"Tom", 25}