提交 91d826cc 编写于 作者: J James Miranda

Translation for section 2.1, including code

上级 1f81ba42
......@@ -24,30 +24,30 @@ Isto irá imprimir a seguinte informação.
Uma coisa que você precisa entender em primeiro lugar é que os programas Go são compostos de pacotes (identificados pela palavra-chave `package`).
`package <pkgName>` que no nosso exemplo é `package main`, identifica que esse código pertence ao pacote `main` e a palavra `main` indica que esse pacote será compilado em um programa ao invés de um pacote com extensão `.a`.
`package <pkgName>` define o nome do pacote, no nosso exemplo temos `package main` que identifica que esse código pertence ao pacote `main` e a palavra `main` indica que esse pacote será compilado em um programa ao invés de um pacote com extensão `.a`.
Todo programa executável possui um, e somente um, pacote `main` e este último precisa conter uma função nomeada como `main` sem nenhum argumento ou valores de retorno.
Para exibir a mensagem `Hello, world…`, foi utilizada uma função chamada `Printf`. Esta função faz parte do pacote `fmt`, então nós importamos esse pacote na terceira linha do código usando a instrução `import "fmt"`.
The way to think about packages in Go is similar to Python, and there are some advantages: Modularity (break up your program into many modules) and reusability (every module can be reused in many programs). We just talked about concepts regarding packages, and we will make our own packages later.
A maneira de pensar nos pacotes em Go é similar a linguagem Python, e traz a seguintes vantagens: Modularidade (quebrar seu programa em vários módulos) e Reusabilidade (todos os módulos podem ser usados em diferentes lugares). Estes são os principais tópicos que precisamos falar sobre pacotes, e nós vamos fazer os nossos próprios pacotes mais tarde.
On the fifth line, we use the keyword `func` to define the `main` function. The body of the function is inside of `{}`, just like C, C++ and Java.
Na quinta linha, nós usamos a palavra `func` para definir a função `main` e o corpo da função está dentro de chaves(`{}`), da mesma forma que é feito em C, C++ e Java.
As you can see, there are no arguments. We will learn how to write functions with arguments in just a second, and you can also have functions that have no return value or have several return values.
Como você pode notar, não temos argumentos. Nós iremos ver como escrever funções com argumentos em breve, assim como funções que possuem zero, um ou vários valores de retorno também.
On the sixth line, we called the function `Printf` which is from the package `fmt`. This was called by the syntax `<pkgName>.<funcName>`, which is very like Python-style.
Na sexta linha, chamamos a função `Printf` que vem do pacote `fmt`. Este tipo de função é invocada pela sintaxe `<pkgName>.<funcName>`, que é muito parecido com o estilo Python.
As we mentioned in chapter 1, the package's name and the name of the folder that contains that package can be different. Here the `<pkgName>` comes from the name in `package <pkgName>`, not the folder's name.
Como mencionado no Capítulo 1, o nome do pacote e o nome da pasta que o contém podem ser diferentes. O nome do pacote vem do `<pkgName>` em `package <pkgName>`, não do nome da pasta.
You may notice that the example above contains many non-ASCII characters. The purpose of showing this is to tell you that Go supports UTF-8 by default. You can use any UTF-8 character in your programs.
Finalmente, você pode notar que o exemplo acima contém vários caracteres não-ASCII (que não estão na tabela ASCII). O objetivo é demonstrar que a lingaugem Go tem suporte nativo a UTF-8. Você pode usar qualquer caracter UTF-8 em seus programas.
## Conclusion
## Conclusão
Go uses `package` (like modules in Python) to organize programs. The function `main.main()` (this function must be in the `main` package) is the entry point of any program. Go supports UTF-8 characters because one of the creators of Go is a creator of UTF-8, so Go has supported multiple languages from the time it was born.
Go usa pacotes (semelhantes aos módulos em Python) para organizar os programas. A função `main.main()` (função que precisa estar no pacote `main`) é o ponto de entrada para todos os programas. Go suporta UTF-8 de forma nativa, pois um dos criadores da linguagem é também o criador do UTF-8, logo Go possui suporte para vários idiomas (mult-lang) por padrão.
## Links
- [Directory](preface.md)
- Previous section: [Go basic knowledge](02.0.md)
- Next section: [Go foundation](02.2.md)
- [Sumário](preface.md)
- Sessão anterior: [Conhecimento básico de Go](02.0.md)
- Próxima sessão: [Fundamentos Go](02.2.md)
# 2.2 Go foundation
# 2.2 Fundamentos Go
In this section, we are going to teach you how to define constants, variables with elementary types and some skills in Go programming.
......@@ -15,12 +15,12 @@ Define multiple variables.
// define three variables which types are "type"
var vname1, vname2, vname3 type
Define a variable with initial value.
// define a variable with name “variableName”, type "type" and value "value"
var variableName type = value
Define multiple variables with initial values.
/*
......@@ -28,7 +28,7 @@ Define multiple variables with initial values.
vname1 is v1, vname2 is v2, vname3 is v3
*/
var vname1, vname2, vname3 type = v1, v2, v3
Do you think that it's too tedious to define variables use the way above? Don't worry, because the Go team has also found this to be a problem. Therefore if you want to define variables with initial values, we can just omit the variable type, so the code will look like this instead:
/*
......@@ -36,7 +36,7 @@ Do you think that it's too tedious to define variables use the way above? Don't
vname1 is v1,vname2 is v2,vname3 is v3
*/
var vname1, vname2, vname3 = v1, v2, v3
Well, I know this is still not simple enough for you. Let's see how we fix it.
/*
......@@ -44,13 +44,13 @@ Well, I know this is still not simple enough for you. Let's see how we fix it.
vname1 is v1,vname2 is v2,vname3 is v3
*/
vname1, vname2, vname3 := v1, v2, v3
Now it looks much better. Use `:=` to replace `var` and `type`, this is called a brief statement. But wait, it has one limitation: this form can only be used inside of functions. You will get compile errors if you try to use it outside of function bodies. Therefore, we usually use `var` to define global variables and we can use this brief statement in `var()`.
`_` (blank) is a special variable name. Any value that is given to it will be ignored. For example, we give `35` to `b`, and discard `34`.( ***This example just show you how it works. It looks useless here because we often use this symbol when we get function return values.*** )
_, b := 34, 35
If you don't use variables that you've defined in your program, the compiler will give you compilation errors. Try to compile the following code and see what happens.
package main
......@@ -58,7 +58,7 @@ If you don't use variables that you've defined in your program, the compiler wil
func main() {
var i int
}
## Constants
So-called constants are the values that are determined during compile time and you cannot change them during runtime. In Go, you can use number, boolean or string as types of constants.
......@@ -66,7 +66,7 @@ So-called constants are the values that are determined during compile time and y
Define constants as follows.
const constantName = value
// you can assign type of constants if it's necessary
// you can assign type of constants if it's necessary
const Pi float32 = 3.1415926
More examples.
......@@ -75,7 +75,7 @@ More examples.
const i = 10000
const MaxThread = 10
const prefix = "astaxie_"
## Elementary types
### Boolean
......@@ -90,7 +90,7 @@ In Go, we use `bool` to define a variable as boolean type, the value can only be
valid := false // brief statement of variable
available = true // assign value to variable
}
### Numerical types
Integer types include both signed and unsigned integer types. Go has `int` and `uint` at the same time, they have same length, but specific length depends on your operating system. They use 32-bit in 32-bit operating systems, and 64-bit in 64-bit operating systems. Go also has types that have specific length including `rune`, `int8`, `int16`, `int32`, `int64`, `byte`, `uint8`, `uint16`, `uint32`, `uint64`. Note that `rune` is alias of `int32` and `byte` is alias of `uint8`.
......@@ -112,7 +112,7 @@ That's all? No! Go supports complex numbers as well. `complex128` (with a 64-bit
var c complex64 = 5+5i
//output: (5+5i)
fmt.Printf("Value is: %v", c)
### String
We just talked about how Go uses the UTF-8 character set. Strings are represented by double quotes `""` or backticks ``` `` ```.
......@@ -130,7 +130,7 @@ It's impossible to change string values by index. You will get errors when you c
var s string = "hello"
s[0] = 'c'
What if I really want to change just one character in a string? Try following code.
s := "hello"
......@@ -138,25 +138,25 @@ What if I really want to change just one character in a string? Try following co
c[0] = 'c'
s2 := string(c) // convert back to string type
fmt.Printf("%s\n", s2)
You use the `+` operator to combine two strings.
s := "hello,"
m := " world"
a := s + m
fmt.Printf("%s\n", a)
and also.
s := "hello"
s = "c" + s[1:] // you cannot change string values by index, but you can get values instead.
fmt.Printf("%s\n", s)
What if I want to have a multiple-line string?
m := `hello
world`
`` ` will not escape any characters in a string.
### Error types
......@@ -167,7 +167,7 @@ Go has one `error` type for purpose of dealing with error messages. There is als
if err != nil {
fmt.Print(err)
}
### Underlying data structure
The following picture comes from an article about [Go data structure](http://research.swtch.com/godata) in [Russ Cox Blog](http://research.swtch.com/). As you can see, Go utilizes blocks of memory to store data.
......@@ -194,7 +194,7 @@ Basic form.
var i int
var pi float32
var prefix string
Group form.
import(
......@@ -213,7 +213,7 @@ Group form.
pi float32
prefix string
)
Unless you assign the value of constant is `iota`, the first value of constant in the group `const()` will be `0`. If following constants don't assign values explicitly, their values will be the same as the last one. If the value of last constant is `iota`, the values of following constants which are not assigned are `iota` also.
### iota enumerate
......@@ -228,8 +228,8 @@ Go has one keyword called `iota`, this keyword is to make `enum`, it begins with
)
const v = iota // once iota meets keyword `const`, it resets to `0`, so v = 0.
const (
const (
e, f, g = iota, iota, iota // e=0,f=0,g=0 values of iota are same in one line.
)
......@@ -247,7 +247,7 @@ The reason that Go is concise because it has some default behaviors.
`array` is an array obviously, we define one as follows.
var arr [n]type
in `[n]type`, `n` is the length of the array, `type` is the type of its elements. Like other languages, we use `[]` to get or set element values within arrays.
var arr [10]int // an array of type [10]int
......@@ -255,7 +255,7 @@ in `[n]type`, `n` is the length of the array, `type` is the type of its elements
arr[1] = 13 // assign value to element
fmt.Printf("The first element is %d\n", arr[0]) // get element value, it returns 42
fmt.Printf("The last element is %d\n", arr[9]) //it returns default value of 10th element in this array, which is 0 in this case.
Because length is a part of the array type, `[3]int` and `[4]int` are different types, so we cannot change the length of arrays. When you use arrays as arguments, functions get their copies instead of references! If you want to use references, you may want to use `slice`. We'll talk about later.
It's possible to use `:=` when you define arrays.
......@@ -273,7 +273,7 @@ You may want to use arrays as arrays' elements. Let's see how to do this.
// The declaration can be written more concisely as follows.
easyArray := [2][4]int{{1, 2, 3, 4}, {5, 6, 7, 8}}
Array underlying data structure.
![](images/2.2.array.png?raw=true)
......@@ -292,7 +292,7 @@ In many situations, the array type is not a good choice -for instance when we do
Then we define a `slice`, and initialize its data.
slice := []byte {'a', 'b', 'c', 'd'}
`slice` can redefine existing slices or arrays. `slice` uses `array[i:j]` to slice, where `i` is the start index and `j` is end index, but notice that `array[j]` will not be sliced since the length of the slice is `j-i`.
// define an array with 10 elements whose types are bytes
......@@ -308,7 +308,7 @@ Then we define a `slice`, and initialize its data.
// 'b' is another slice of array ar
b = ar[3:5]
// now 'b' has elements ar[3] and ar[4]
Notice the differences between `slice` and `array` when you define them. We use `[…]` to let Go calculate length but use `[]` to define slice only.
Their underlying data structure.
......@@ -379,7 +379,7 @@ Let's see some code. The 'set' and 'get' values in `map` are similar to `slice`,
// another way to define map
numbers := make(map[string]int)
numbers["one"] = 1 // assign value by key
numbers["ten"] = 10
numbers["ten"] = 10
numbers["three"] = 3
fmt.Println("The third number is: ", numbers["three"]) // get values
......@@ -414,7 +414,7 @@ As I said above, `map` is a reference type. If two `map`s point to same underlyi
m["Hello"] = "Bonjour"
m1 := m
m1["Hello"] = "Salut" // now the value of m["hello"] is Salut
### make, new
`make` does memory allocation for built-in models, such as `map`, `slice`, and `channel`, while `new` is for types' memory allocation.
......@@ -446,7 +446,7 @@ Zero-value does not mean empty value. It's the value that variables default to i
float64 0 //length is 8 byte
bool false
string ""
## Links
- [Directory](preface.md)
......
<<<<<<< HEAD
// Código de exemplo para o Capítulo 1.2 do "Build Web Application with Golang"
// Código de exemplo para o Capítulo 1.2 do "Build Web Application with Golang"
// Propósito: Execute este arquivo para verificar se o seu workspace está corretamente configurado.
// Para executar, navegue até o diretório onde ele estiver salvo e digite no console `go run main.go`
// Se o texto "Hello World" não aparecer, então configure seu ambiente novamente.
=======
// Example code for Chapter 1.2 from "Build Web Application with Golang"
// Purpose: Run this file to check if your workspace is setup correctly.
// To run, navigate to the current directory in a console and type `go run main.go`
// If the text "Hello World" isn't shown, then setup your workspace again.
>>>>>>> eead24cf064976b648de5826eab51880c803b0fa
package main
package main
import (
"fmt"
......
// Example code for Chapter ? from "Build Web Application with Golang"
// Purpose: Hello world example demonstrating UTF-8 support.
// To run in the console, type `go run main.go`
// You're missing language fonts, if you're seeing squares or question marks.
// Código de exemplo para o Capítulo 2.1 do "Build Web Application with Golang"
// Propósito: Exemplo de Hello world demonstrando suporte para UTF-8.
// Para executar, navegue até o diretório onde ele estiver salvo e digite no console `go run main.go`
// Se você receber quadrados ou pontos de interrogação, possivelemente você não tenha as fontes instaladas.
package main
import "fmt"
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册