Merge remote-tracking branch 'upstream/master'

This commit is contained in:
Goryudyuma
2015-08-28 20:50:18 +09:00
43 changed files with 132 additions and 63 deletions

View File

@@ -60,7 +60,7 @@ Características de LiteIDE
- Entorno de compilación
Cambia la configuración en LiteIDE para que se ajuste a tu sistema operativo.
En Windows y usando al versión de 64-bits de Go, debes usar win64 cómo la configuración de entorno en la barra de herramientas. Luego escoge `opinion`, busca `LiteEnv` en la lista de la izquierda y abre el archivo `win64.env` en la lista de la derecha.
En Windows y usando al versión de 64-bits de Go, debes usar win64 cómo la configuración de entorno en la barra de herramientas. Luego escoge `Options`, busca `LiteEnv` en la lista de la izquierda y abre el archivo `win64.env` en la lista de la derecha.
GOROOT=c:\go
GOBIN=
@@ -73,7 +73,7 @@ Características de LiteIDE
Reemplaza `GOROOT=c:\go` con tu ruta de instalación de Go y guarda. Si tienes MinGW64, agrega `c:\MinGW64\bin` a la variable de entorno de tu path para soportar `cgo`.
En Linux y usando la versiónd de 64-bits de Go, debes escoger linux64 como la configuración de entorno en la barra de herramientas. Luego escoge `opinion`, busca `LiteEnv` en la lista de la izquierda y abre el archivo `linux64.env` en la lista de la derecha.
En Linux y usando la versiónd de 64-bits de Go, debes escoger linux64 como la configuración de entorno en la barra de herramientas. Luego escoge `Options`, busca `LiteEnv` en la lista de la izquierda y abre el archivo `linux64.env` en la lista de la derecha.
GOROOT=$HOME/go
GOBIN=

View File

@@ -63,7 +63,7 @@ Fonctionnalités de LiteIDE:
Changer de configuration de LiteIDE pour correspondre à votre système d'exploitation
Dans Windows avec la version 64-bit de Go, vous devriez utiliser win64 comme configuration de votre environnement dans la barre d'outils.
Ensuite, choisissez `option`, puis `LiteEnv` dans la liste de gauche et sélectionnez le fichier `win64.env` dans la liste de droite.
Ensuite, choisissez `Options`, puis `LiteEnv` dans la liste de gauche et sélectionnez le fichier `win64.env` dans la liste de droite.
GOROOT=c:\go
GOBIN=
@@ -77,7 +77,7 @@ Fonctionnalités de LiteIDE:
Modifiez `GOROOT=c:\go` par le chemin de votre installation Go, puis sauvegardez. Si vous avez MinGW64, ajoutez `c:\MinGW64\bin` au chemin de votre variable d'environnement pour le support de `cgo`.
Pour Linux avec Go en version 64-bit, choisissez linux64 comme configuration de votre environnement dans la barre d'outils.
Ensuite, choisissez `opinion`, puis `LiteEnv` dans la liste de gauche et sélectionnez le fichier `linux64.env` dans la liste de droite.
Ensuite, choisissez `Options`, puis `LiteEnv` dans la liste de gauche et sélectionnez le fichier `linux64.env` dans la liste de droite.
GOROOT=$HOME/go
GOBIN=

View File

@@ -2,38 +2,36 @@
## $GOPATH
Go commands all rely on one important environment variable called $GOPATH. Notice that this is not the $GOROOT variable where Go is installed. This variable points to the workspace of Go on your computer (I use this path on my computer; if you don't have the same directory structure, please replace by yourself).
Os comandos em Go dependem de uma variável do sistema chama $GOPATH. Note que não é a variável $GOROOT, responsável pelo local aonde a linguagem está instalada.
Essa variável($GOPATH), marca a localização do ambiente de trabalho Go.
Em sistema UNIX-Linux, a variável do sistema deverá ser configurada da seguinte forma no arquivo `.bash_profile`
In Unix-like systems, the variable should be used like this:
export GOPATH=/home/apple/mygo
In Windows, you need to create a new environment variable called GOPATH, then set its value to `c:\mygo`( ***This value depends on where your workspace is located*** )
No Windows você precisa criar uma nova variável de ambiente chamada GOPATH, e configura-la para o diretório de trabalho, por exemplo: `c:\mygo`
It's OK to have more than one path (workspace) in $GOPATH, but remember that you have to use `:`(`;` in Windows) to break them up. At this point, `go get` will save the content to your first path in $GOPATH.
É comum ter mais de um Workspace no seu $GOPATH, mas lembre-se de usar `:`(`;` no Windows) para delimitar os diretórios. Com o $GOPATH configurado você já poderá realizar o download de pacotes externos utilizando o `go get`.
In $GOPATH, you must have three folders as follows.
Dentro do seu $GOPATH, deverá ter os seguintes diretórios:
- `src` for source files whose suffix is .go, .c, .g, .s.
- `pkg` for compiled files whose suffix is .a.
- `bin` for executable files
- `src` Para arquivos de código fonte .go, .c, .g, .s.
- `pkg` Para bibliotecas compiladas .a.
- `bin` Para executáveis
In this book, I use `mygo` as my only path in $GOPATH.
Nesse livro, vamos utilizar a pasta: `mygo` como único ambiente no $GOPATH.
## Package directory
## Diretórios de pacotes
Crie um novo arquivo chamado sqrt.go dentro da pasta `$GOPATH/src/mymath/sqrt.go` (Note que também foi criado um diretório chamado 'mymath', no qual deverá ser o nome do nosso pacote)
Create package source files and folders like `$GOPATH/src/mymath/sqrt.go` (`mymath` is the package name) ( ***Author uses `mymath` as his package name, and same name for the folder where contains package source files***)
Every time you create a package, you should create a new folder in the `src` directory. Folder names are usually the same as the package that you are going to use. You can have multi-level directories if you want to. For example, if you create the directory `$GOPATH/src/github.com/astaxie/beedb`, then the package path would be `github.com/astaxie/beedb`. The package name will be the last directory in your path, which is `beedb` in this case.
Execute following commands. ( ***Now author goes back to talk examples*** )
Todas as vezes que um novo pacote for criado, você deverá criar uma pasta com seu nome dentro de `src`. O nome das pastas costumam ter o mesmo nome do pacote que será utilizado. Você pode ter quantas pastas quiser, por exemplo: Se você criar uma pasta `$GOPATH/src/github.com/astaxie/beedb`, então seu pacote será `github.com/astaxie/beedb`. O nome do pacote sempre será o último, no caso do exemplo citado: `beedb`
Execute os comandos abaixo:
cd $GOPATH/src
mkdir mymath
Create a new file called `sqrt.go`, type following content to your file.
// Source code of $GOPATH/src/mymath/sqrt.go
Crie um novo arquivo chamado `sqrt.go` e ponha o seguinte conteúdo:
// Código fonte de $GOPATH/src/mymath/sqrt.go
package mymath
func Sqrt(x float64) float64 {
@@ -44,35 +42,34 @@ Create a new file called `sqrt.go`, type following content to your file.
return z
}
Now my package directory has been created and its code has been written. I recommend that you use the same name for your packages as their corresponding directories, and that the directories contain all of the package source files.
Agora o diretório e código fonte do meu pacote foi criado. Recomendo que utilize o nome do pacote correspondendo ao diretório.
## Compile packages
## Compilando pacotes
We've already created our package above, but how do we compile it for practical purposes? There are two ways to do this.
Agora que nós criamos nosso pacote acima, como vamos utilizado de modo prático? Existem duas maneiras de fazer isso.
1. Switch your work path to the directory of your package, then execute the `go install` command.
2. Execute the above command except with a file name, like `go install mymath`.
After compiling, we can open the following folder.
1. Mude para o diretório do seu pacote e execute o comando `go install`.
2. Execute o comando acima, utilizando o nome do arquivo sem extenção, exemplo: `go install mymath`.
Após compilado, podemos ve-lo na seguinte pasta:
cd $GOPATH/pkg/${GOOS}_${GOARCH}
// you can see the file was generated
// O arquivo do pacote gerado com a extenção .a
mymath.a
The file whose suffix is `.a` is the binary file of our package. How do we use it?
Nosso arquivo foi gerado com a extenção `.a`. Isso é o arquivo binário, como vamos utiliza-lo?
Obviously, we need to create a new application to use it.
Obviamente teremos que criar uma nova aplicação para utilizar.
Create a new application package called `mathapp`.
Crie uma nova aplicação chamada `mathapp`
cd $GOPATH/src
mkdir mathapp
cd mathapp
vim main.go
code
Código fonte:
//$GOPATH/src/mathapp/main.go source code.
//$GOPATH/src/mathapp/main.go código fonte.
package main
import (
@@ -81,25 +78,25 @@ code
)
func main() {
fmt.Printf("Hello, world. Sqrt(2) = %v\n", mymath.Sqrt(2))
fmt.Printf("Olá, mundo. Sqrt(2) = %v\n", mymath.Sqrt(2))
}
To compile this application, you need to switch to the application directory, which in this case is `$GOPATH/src/mathapp`, then execute the `go install` command. Now you should see an executable file called `mathapp` was generated in the directory `$GOPATH/bin/`. To run this program, use the `./mathapp` command. You should see the following content in your terminal.
Para compilar nossa aplicação, deveremos alterar o código fonte de diretório, nesse caso para `$GOPATH/src/mathapp` e executar o comando `go install`. Agora teremos um arquivo executável dentro da pasta `$GOPATH/bin/`. Para executarmos basta: `./mathapp` no terminal, e você deverá ver o seguinte retorno:
Hello world. Sqrt(2) = 1.414213562373095
Olá, mundo. Sqrt(2) = 1.414213562373095
## Install remote packages
## Instalando pacotes remotamente
Go has a tool for installing remote packages, which is a command called `go get`. It supports most open source communities, including Github, Google Code, BitBucket, and Launchpad.
Go tem uma ferramente para utilizar pacotes remotos, chamada `go get`. Ela é suportada por grandes comunidades código aberto, incluindo: Github, Google Code, Bitbucket e Launchpad.
go get github.com/astaxie/beedb
You can use `go get -u …` to update your remote packages and it will automatically install all the dependent packages as well.
Você pode utilizar o parâmetro `-u` para a atualizar os pacotes já existentes, por exemplo: `go get -u …`.
This tool will use different version control tools for different open source platforms. For example, `git` for Github and `hg` for Google Code. Therefore, you have to install these version control tools before you use `go get`.
After executing the above commands, the directory structure should look like following.
O `go get` utiliza as ferramentas de versionamento código berto mais utilizadas do mercado como `git` para o GitHub e o `hg` para o Google Code.
Antes de utilizar o `go get` certifique-se de ter instado ao menos uma delas. (Nota do tradutor: Recomendo utilizar Git)
Após a execução do comando acima, você deverá ter a seguinte estrutura de diretórios:
$GOPATH
src
|-github.com
@@ -111,20 +108,20 @@ After executing the above commands, the directory structure should look like fol
|-astaxie
|-beedb.a
Actually, `go get` clones source code to the $GOPATH/src of the local file system, then executes `go install`.
O comando `go get` clona o código fonte e dependencias para o seu $GOPATH/src e instala os pacote com `go install`
You can use remote packages in the same way that we use local packages.
Você também pode utilizar pacotes de terceiros através de imports no código fonte da aplicação:
import "github.com/astaxie/beedb"
## Directory complete structure
## Estrutura de diretórios completa
If you've followed all of the above steps, your directory structure should now look like the following.
Se você seguiu todos os passos anteriores corretamente, sua estrurura de diretórios deverá ser algo semelhando a isso:
bin/
mathapp
pkg/
${GOOS}_${GOARCH}, such as darwin_amd64, linux_amd64
${GOOS}_${GOARCH}, A arquitetura do seu sistema: darwin_amd64, linux_amd64
mymath.a
github.com/
astaxie/
@@ -141,11 +138,12 @@ If you've followed all of the above steps, your directory structure should now l
util.go
Now you are able to see the directory structure clearly; `bin` contains executable files, `pkg` contains compiled files and `src` contains package source files.
Agora que exclarevemos como Go gerencia dependencias e código fonte, vamos recaptular de forma rápida a estrutura; `bin` contém os executaveis, `pkg` bibliotecas ou pacotes compilados, `src` código fonte da sua aplicação e pacotes.
(The format of environment variables in Windows is `%GOPATH%`, however this book mainly follows the Unix-style, so Windows users need to replace these yourself.)
(O GOPATH no Windows é exibido como: `%GOPATH%`, como esse livro tem um foco em sistemas UNIX-Like, usuários Windows deverão realizar futuros ajustes para que tudo ocorra como esperado)
## Links
- [Directory](preface.md)
- Previous section: [Installation](01.1.md)
- Next section: [Go commands](01.3.md)
- [Sumário](preface.md)
- Sessão anterior: [Instalação](01.1.md)
- Próxima sessão: [Comandos em Go](01.3.md)

View File

@@ -6,4 +6,4 @@
- [Содержание](preface.md)
- Предыдущий раздел: [Инструменты разработки для Go](01.4.md)
- Следующий раздел: [Основы Go](02.0.md)
- Следующий раздел: [Введение в Go](02.0.md)

17
ru/02.0.md Normal file
View File

@@ -0,0 +1,17 @@
# 2 Введение в Go
Go - компилируемый системный язык программирования, и он относится к С-подобным языкам. Однако, скорость его компиляции намного выше. Он имеет всего 25 ключевых слов... даже меньше чем букв в английском алфавите! Давайте взглянем на эти ключевые слова прежде чем мы начнем.
break default func interface select
case defer go map struct
chan else goto package switch
const fallthrough if range type
continue for import return var
В этой главе, я собираюсь научить вас основам Go. Вы обнаружите, насколько лаконичен язык Go, и как превосходна его архитектура. Программирование на Go может быть по-настоящему веселым. После того, как вы закончите эту главу, вы будете знакомы с упомянутыми ключевыми словами.
## Ссылки
- [Содержание](preface.md)
- Предыдущий раздел: [Глава 1 Итоги раздела](01.4.md)
- Следующий раздел: ["Привет, Go"](02.1.md)

54
ru/02.1.md Normal file
View File

@@ -0,0 +1,54 @@
# 2.1 Привет, Go
Прежде чем мы начнем конструировать приложение на Go, нам необходимо научиться писать простые программы. Вы не сможете построить здание, не узнав, сперва, как проложить фундамент. Вследствие чего, в этом разделе мы изучим базовый синтакс для запуска простой программы.
## Программа
Согласно международной практике, изучение языков программирования принято начинать с написания программы, которая выводит текст "Hello, World".
Вы готовы? Let's Go!
package main
import "fmt"
func main() {
fmt.Printf("Hello, world or 你好,世界 or καλημ ́ρα κóσμ or こんにちは世界 or Привет, мир\n")
}
Это выводит следующую информацию.
Hello, world or 你好,世界 or καλημ ́ρα κóσμ or こんにちは世界 or Привет, мир
## Объяснение
Во-первых программы в Go состоят из `package` (пакетов).
`package <pkgName>` (В данном случае `package main`) говорит нам о том, что этот исходный файл принадлежит к `main` пакету. А ключевое слово `main`, что данный пакет должен компилироваться в программу, а не в пакет файлов с расширением `.a`.
Каждая исполняемая программа имеет один и только один `main` пакет, а также вам необходимо реализовать функцию `main` без аргументов и возвращаемых значений.
Чтобы вывести `Hello, world…`, мы вызвали функцию `Printf`. Эта функция находится в пакете `fmt`, поэтому нам надо импортировать этот пакет, что мы и делаем в третьей строчке кода - `import "fmt"`.
Пакеты в Go похожи на аналогичные в Python, вот несколько преимуществ пакетов:
Модульность (разбить программу на несколько модулей) и повторное использование (каждый модуль может быть использован во множестве программ). Сейчас мы просто рассмотрели общее представление пакетов, и чуть позже напишем свой собственный пакет.
В пятой строке мы использовали ключевое слово `func` для определения функции `main`. Тело функции находится внутри `{}`, прямо как в C, C++ и Java.
Как вы видите она не принимает ни один аргумент. Мы научимся писать функции, принимающие аргументы всего через минуту, а также функции которые не возвращают значение или возращают несколько.
В шестой строке мы вызываем функцию `Printf`, которая находится в пакете `fmt`. Она была вызвана, используя синтаксис `<pkgName>.<funcName>` (`<имя пакета>.<имя функции>`), в Python-стиле.
Как мы упоминали в 1 главе, имя пакета и имя папки (которая содержит этот пакет) могут быть различными. Здесь `<pkgName>` (`<имя пакета>`) исходит из пакета, а не из имени папки.
Как вы могли заметить, пример выше содержит множество символов, которых нет в таблице ASCII. Это было нужно для того, чтобы продемонстрировать, что Go поддерживает UTF-8 по-умолчанию. Вы можете использовать в ваших программах любой символ из UTF-8.
## Заключение
Go использует `package` (пакет) для структурирования программ. Функция `main.main()` (эта функция находится в пакете `main`) входной пункт каждой программы. Go поддерживает стандарт UTF-8, так как один из создателей Go является также одним из создателей UTF-8, так что Go поддерживает множество языков с самого рождения.
## Ссылки
- [Содержание](preface.md)
- Предыдущий раздел: [Введение в Go](02.0.md)
- Следующий раздел: [Основы Go](02.2.md)

Binary file not shown.

Before

Width:  |  Height:  |  Size: 190 KiB

After

Width:  |  Height:  |  Size: 152 KiB

BIN
ru/images/3.1.dns2_Ru.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 177 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 60 KiB

After

Width:  |  Height:  |  Size: 51 KiB

BIN
ru/images/3.1.web2_Ru.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 55 KiB

After

Width:  |  Height:  |  Size: 51 KiB

BIN
ru/images/8.4.rpc_Ru.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 78 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 33 KiB

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 31 KiB

After

Width:  |  Height:  |  Size: 30 KiB

BIN
ru/images/navi10_Ru.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 35 KiB

After

Width:  |  Height:  |  Size: 32 KiB

BIN
ru/images/navi11_Ru.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 34 KiB

After

Width:  |  Height:  |  Size: 30 KiB

BIN
ru/images/navi12_Ru.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 47 KiB

After

Width:  |  Height:  |  Size: 36 KiB

BIN
ru/images/navi13_Ru.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 44 KiB

After

Width:  |  Height:  |  Size: 37 KiB

BIN
ru/images/navi14_Ru.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 54 KiB

BIN
ru/images/navi1_Ru.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 43 KiB

After

Width:  |  Height:  |  Size: 40 KiB

BIN
ru/images/navi2_Ru.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 38 KiB

After

Width:  |  Height:  |  Size: 34 KiB

BIN
ru/images/navi3_Ru.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 39 KiB

After

Width:  |  Height:  |  Size: 32 KiB

BIN
ru/images/navi4_Ru.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 53 KiB

After

Width:  |  Height:  |  Size: 42 KiB

BIN
ru/images/navi5_Ru.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 39 KiB

After

Width:  |  Height:  |  Size: 38 KiB

BIN
ru/images/navi6_Ru.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 41 KiB

After

Width:  |  Height:  |  Size: 37 KiB

BIN
ru/images/navi7_Ru.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 30 KiB

After

Width:  |  Height:  |  Size: 35 KiB

BIN
ru/images/navi8_Ru.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 45 KiB

After

Width:  |  Height:  |  Size: 37 KiB

BIN
ru/images/navi9_Ru.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

View File

@@ -60,7 +60,7 @@ LiteIDE özellikleri:
- Derleme Ortamı
Ayarlamalarınızı işletim sisteminize uygun bir şekilde yapın.
Go'nun 64-bitlik versiyonunu windowsta koşturuyorsanız, araç çubugunda konfigürasyon ortamı olarak win64 olarak ayarlayın.`option` menüsü altındaki `liteEnv` sekmesine tıklayın ve `win64.env` adlı dosyayıın.
Go'nun 64-bitlik versiyonunu windowsta koşturuyorsanız, araç çubugunda konfigürasyon ortamı olarak win64 olarak ayarlayın.`Options` menüsü altındaki `liteEnv` sekmesine tıklayın ve `win64.env` adlı dosyayıın.
GOROOT=c:\go
GOBIN=
@@ -73,7 +73,7 @@ LiteIDE özellikleri:
`GOROOT=c:\go` satırını kendi Go kurulu dizininize ayarlayın ve kaydedin. MinGW64 kullanıyorsanız,`c:\MinGW64\bin`yi `cgo` desteği için PATH değişkenine ekleyin.
Go'nun 64-bitlik linuxta koşturuyorsanız, araç çubuğunda kanfigürasyon ortamı olarak linux64 olarak ayarlayın. `option` menüsü altındaki `liteEnv` sekmesine tıklayın ve `linux64.env` adlı dosyayıın.
Go'nun 64-bitlik linuxta koşturuyorsanız, araç çubuğunda kanfigürasyon ortamı olarak linux64 olarak ayarlayın. `Options` menüsü altındaki `liteEnv` sekmesine tıklayın ve `linux64.env` adlı dosyayıın.
GOROOT=$HOME/go
GOBIN=

View File

@@ -149,22 +149,22 @@ Go里面最强大的一个控制逻辑就是`for`,它即可以用来循环读
integer := 6
switch integer {
case 4:
case 4:
fmt.Println("The integer was <= 4")
fallthrough
case 5:
case 5:
fmt.Println("The integer was <= 5")
fallthrough
case 6:
case 6:
fmt.Println("The integer was <= 6")
fallthrough
case 7:
case 7:
fmt.Println("The integer was <= 7")
fallthrough
case 8:
case 8:
fmt.Println("The integer was <= 8")
fallthrough
default:
default:
fmt.Println("default case")
}