init commit

This commit is contained in:
badkaktus 2019-10-05 16:12:52 +03:00
parent 61e8dde1c1
commit 74bd8410fd
24 changed files with 255 additions and 247 deletions

View File

@ -1,26 +1,22 @@
# Go by Example # Go by Example
Content and build toolchain for [Go by Example](https://gobyexample.com), Набор инструментов для генерации [Go в примерах](https://gobyexample.su),
a site that teaches Go via annotated example programs. сайта который помогает изучать язык Go на примерах.
### Overview ### Обзор
The Go by Example site is built by extracting code and Сайт **Go в Примерах** генерируется на основании кода и комментариев
comments from source files in `examples` and rendering в файлах в папке `examples` и рендерится на основании шаблонов в папке
them via the `templates` into a static `public` `templates`. Готовый сайт находится в `public`.
directory. The programs implementing this build process Программы, реализующие процесс сборки находятся в `tools`,
are in `tools`, along with some vendor'd dependencies вместе с некоторыми вендорными зависимостями в `vendor`.
in `vendor`.
The built `public` directory can be served by any
static content system. The production site uses S3 and
CloudFront, for example.
### Building ### Building
[![Build Status](https://travis-ci.com/mmcgrana/gobyexample.svg "Travis CI status")](https://travis-ci.com/mmcgrana/gobyexample) [![Build Status](https://travis-ci.com/mmcgrana/gobyexample.svg "Travis CI status")](https://travis-ci.com/mmcgrana/gobyexample)
To build the site you'll need Go and Python installed. Run: Для создания сайта вам понадобятся Go и Python. Выполните:
```console ```console
$ go get github.com/russross/blackfriday $ go get github.com/russross/blackfriday
@ -28,15 +24,15 @@ $ tools/build
$ open public/index.html $ open public/index.html
``` ```
To build continuously in a loop: Непрерывное построение в цикле:
```console ```console
$ tools/build-loop $ tools/build-loop
``` ```
### Publishing ### Публикация
To upload the site: Загрузка сайта (AWS):
```console ```console
$ gem install aws-sdk $ gem install aws-sdk
@ -45,18 +41,18 @@ $ export AWS_SECRET_ACCESS_KEY=...
$ tools/upload $ tools/upload
``` ```
### License ### Лицензии
This work is copyright Mark McGranaghan and licensed under a Это работа защищена копирайтом Mark McGranaghan и соответствует лицензии
[Creative Commons Attribution 3.0 Unported License](http://creativecommons.org/licenses/by/3.0/). [Creative Commons Attribution 3.0 Unported License](http://creativecommons.org/licenses/by/3.0/).
The Go Gopher is copyright [Renée French](http://reneefrench.blogspot.com/) and licensed under a Go Gopher защищен [Renée French](http://reneefrench.blogspot.com/) и соответствует лицензии
[Creative Commons Attribution 3.0 Unported License](http://creativecommons.org/licenses/by/3.0/). [Creative Commons Attribution 3.0 Unported License](http://creativecommons.org/licenses/by/3.0/).
### Translations ### Переводы
Contributor translations of the Go by Example site are available in: Авторские переводы сайта Go by Example доступны в:
* [Chinese](https://gobyexample.xgwang.me/) by [xg-wang](https://github.com/xg-wang/gobyexample) * [Chinese](https://gobyexample.xgwang.me/) by [xg-wang](https://github.com/xg-wang/gobyexample)
* [Czech](http://gobyexamples.sweb.cz/) by [martinkunc](https://github.com/martinkunc/gobyexample-cz) * [Czech](http://gobyexamples.sweb.cz/) by [martinkunc](https://github.com/martinkunc/gobyexample-cz)
@ -64,6 +60,7 @@ Contributor translations of the Go by Example site are available in:
* [Italian](http://gobyexample.it) by the [Go Italian community](https://github.com/golangit/gobyexample-it) * [Italian](http://gobyexample.it) by the [Go Italian community](https://github.com/golangit/gobyexample-it)
* [Japanese](http://spinute.org/go-by-example) by [spinute](https://github.com/spinute) * [Japanese](http://spinute.org/go-by-example) by [spinute](https://github.com/spinute)
* [Korean](https://mingrammer.com/gobyexample/) by [mingrammer](https://github.com/mingrammer) * [Korean](https://mingrammer.com/gobyexample/) by [mingrammer](https://github.com/mingrammer)
* [Russian](https://gobyexample.com.ru/) by [badkaktus](https://github.com/badkaktus)
* [Spanish](http://goconejemplos.com) by the [Go Mexico community](https://github.com/dabit/gobyexample) * [Spanish](http://goconejemplos.com) by the [Go Mexico community](https://github.com/dabit/gobyexample)
* [Ukrainian](http://gobyexample.com.ua/) by [butuzov](https://github.com/butuzov/gobyexample) * [Ukrainian](http://gobyexample.com.ua/) by [butuzov](https://github.com/butuzov/gobyexample)

View File

@ -1,19 +1,19 @@
Hello World Hello World
Values Типы данных (Values)
Variables Переменные (Variables)
Constants Константы (Constants)
For Цикл For
If/Else If/Else
Switch Switch
Arrays Массивы (Arrays)
Slices Срезы (Slices)
Maps Карты (Maps)
Range Ряд (Range)
Functions Функции (Functions)
Multiple Return Values Функции с множественным возвратом (Multiple Return Values)
Variadic Functions Функции с переменным числом аргументов (Variadic Functions)
Closures Замыкания (Closures)
Recursion Рекурсия (Recursion)
Pointers Pointers
Structs Structs
Methods Methods

View File

@ -1,5 +1,5 @@
// In Go, an _array_ is a numbered sequence of elements of a // В Go, _массив_ это числовой ряд элементов определенной
// specific length. // длины.
package main package main
@ -7,31 +7,32 @@ import "fmt"
func main() { func main() {
// Here we create an array `a` that will hold exactly // В данном примере мы создаем массив `a`, который
// 5 `int`s. The type of elements and length are both // содержит 5 элементов с типом `int`. Тип элементов
// part of the array's type. By default an array is // и длина являются частью типа массива. По-умолчанию
// zero-valued, which for `int`s means `0`s. // массив заполняется нулевыми значениями, например,
// в случае `int` нулевое значение - 0.
var a [5]int var a [5]int
fmt.Println("emp:", a) fmt.Println("emp:", a)
// We can set a value at an index using the // Мы можем установить значение по индексу элемента
// `array[index] = value` syntax, and get a value with // следующим образом:`array[index] = value`.
// `array[index]`. // Получить значение можно аналогично - `array[index]`.
a[4] = 100 a[4] = 100
fmt.Println("set:", a) fmt.Println("set:", a)
fmt.Println("get:", a[4]) fmt.Println("get:", a[4])
// The builtin `len` returns the length of an array. // Встроенная функция `len` возвращает длину массива.
fmt.Println("len:", len(a)) fmt.Println("len:", len(a))
// Use this syntax to declare and initialize an array // Так можно инициалзировать и заполнить массив
// in one line. // значениеми в одну строку
b := [5]int{1, 2, 3, 4, 5} b := [5]int{1, 2, 3, 4, 5}
fmt.Println("dcl:", b) fmt.Println("dcl:", b)
// Array types are one-dimensional, but you can // Тип `массив` является одномерным. Но вы можете
// compose types to build multi-dimensional data // совмещать типы, для создания многомерных
// structures. // структур.
var twoD [2][3]int var twoD [2][3]int
for i := 0; i < 2; i++ { for i := 0; i < 2; i++ {
for j := 0; j < 3; j++ { for j := 0; j < 3; j++ {

View File

@ -1,5 +1,5 @@
# Note that arrays appear in the form `[v1 v2 v3 ...]` # Обратите внимание, что массивы отображаются в виде
# when printed with `fmt.Println`. # [v1 v2 v3 ...] при выводе с помощью fmt.Println.
$ go run arrays.go $ go run arrays.go
emp: [0 0 0 0 0] emp: [0 0 0 0 0]
set: [0 0 0 0 100] set: [0 0 0 0 100]
@ -8,5 +8,5 @@ len: 5
dcl: [1 2 3 4 5] dcl: [1 2 3 4 5]
2d: [[0 1 2] [1 2 3]] 2d: [[0 1 2] [1 2 3]]
# You'll see _slices_ much more often than arrays in # В Go вы будете встречать _срезы_ гораздо чаще, чем
# typical Go. We'll look at slices next. # массивы. Срезы рассмотрим далее

View File

@ -1,16 +1,15 @@
// Go supports [_anonymous functions_](http://en.wikipedia.org/wiki/Anonymous_function), // Go поддерживает [_анонимные функции_](http://en.wikipedia.org/wiki/Anonymous_function), которые могут образовывать
// which can form <a href="http://en.wikipedia.org/wiki/Closure_(computer_science)"><em>closures</em></a>. // <a href="http://en.wikipedia.org/wiki/Closure_(computer_science)"><em>замыкания</em></a>. Анонимные функции полезны, когда вы хотите
// Anonymous functions are useful when you want to define // определить встроенную функцию, не называя ее.
// a function inline without having to name it.
package main package main
import "fmt" import "fmt"
// This function `intSeq` returns another function, which // Эта функция intSeq возвращает другую функцию, которую
// we define anonymously in the body of `intSeq`. The // мы анонимно определяем в теле intSeq. Возвращенная
// returned function _closes over_ the variable `i` to // функция присваивается в переменную i, чтобы
// form a closure. // сформировать замыкание.
func intSeq() func() int { func intSeq() func() int {
i := 0 i := 0
return func() int { return func() int {
@ -21,20 +20,21 @@ func intSeq() func() int {
func main() { func main() {
// We call `intSeq`, assigning the result (a function) // Мы вызываем `intSeq`, присваивая результат (функцию)
// to `nextInt`. This function value captures its // `nextInt`. Это значение функции фиксирует свое
// own `i` value, which will be updated each time // собственное значение `i`, которое будет обновляться
// we call `nextInt`. // каждый раз, когда мы вызываем `nextInt`.
nextInt := intSeq() nextInt := intSeq()
// See the effect of the closure by calling `nextInt` // Посмотрите, что происходит при вызове `nextInt`
// a few times. // несколько раз.
fmt.Println(nextInt()) fmt.Println(nextInt())
fmt.Println(nextInt()) fmt.Println(nextInt())
fmt.Println(nextInt()) fmt.Println(nextInt())
// To confirm that the state is unique to that // Чтобы подтвердить, что состояние является уникальным
// particular function, create and test a new one. // для этой конкретной функции, создайте и протестируйте
// новую.
newInts := intSeq() newInts := intSeq()
fmt.Println(newInts()) fmt.Println(newInts())
} }

View File

@ -4,5 +4,5 @@ $ go run closures.go
3 3
1 1
# The last feature of functions we'll look at for now is # Последняя особенность функций, которые мы сейчас
# recursion. # рассмотрим, - это рекурсия.

View File

@ -1,5 +1,5 @@
// Go supports _constants_ of character, string, boolean, // В Go _константы_ могут принимать значения следующих типов:
// and numeric values. // строки, числа и логические значения
package main package main
@ -8,28 +8,28 @@ import (
"math" "math"
) )
// `const` declares a constant value. // Для объявления константы используется ключевое слово `const`.
const s string = "constant" const s string = "constant"
func main() { func main() {
fmt.Println(s) fmt.Println(s)
// A `const` statement can appear anywhere a `var` // Оператор `const` может использоваться везде, где может
// statement can. // быть использован оператор `var`.
const n = 500000000 const n = 500000000
// Constant expressions perform arithmetic with // Постоянные выражения выполняют арифметику с
// arbitrary precision. // произвольной точностью.
const d = 3e20 / n const d = 3e20 / n
fmt.Println(d) fmt.Println(d)
// A numeric constant has no type until it's given // Числовая константа не имеет типа до тех пор,
// one, such as by an explicit conversion. // пока ей не присвоен, например, при явном преобразовании.
fmt.Println(int64(d)) fmt.Println(int64(d))
// A number can be given a type by using it in a // Число может использоваться в контексте, который требует
// context that requires one, such as a variable // его, например, присваивание переменной или вызов
// assignment or function call. For example, here // функции. Например, здесь `math.Sin` ожидает
// `math.Sin` expects a `float64`. // `float64`.
fmt.Println(math.Sin(n)) fmt.Println(math.Sin(n))
} }

View File

@ -1,5 +1,5 @@
// `for` is Go's only looping construct. Here are // `for` - это единственный цикл доступный в Go.
// three basic types of `for` loops. // Три стандартных примера использования `for`
package main package main
@ -7,28 +7,28 @@ import "fmt"
func main() { func main() {
// The most basic type, with a single condition. // Стандартный тип с единственным условием
i := 1 i := 1
for i <= 3 { for i <= 3 {
fmt.Println(i) fmt.Println(i)
i = i + 1 i = i + 1
} }
// A classic initial/condition/after `for` loop. // Классическая инициализация/условие/выражение после `for`
for j := 7; j <= 9; j++ { for j := 7; j <= 9; j++ {
fmt.Println(j) fmt.Println(j)
} }
// `for` without a condition will loop repeatedly // `for` без условия будет выполняться бесконечно
// until you `break` out of the loop or `return` from // пока не выполнится `break` (выход из цикла) или
// the enclosing function. // `return`, который завершит функцию с циклом
for { for {
fmt.Println("loop") fmt.Println("loop")
break break
} }
// You can also `continue` to the next iteration of // Так же Вы можете использовать `continue` для
// the loop. // немедленного перехода к следующей итерации цикла
for n := 0; n <= 5; n++ { for n := 0; n <= 5; n++ {
if n%2 == 0 { if n%2 == 0 {
continue continue

View File

@ -1,32 +1,32 @@
// _Functions_ are central in Go. We'll learn about // _Функции_ это сердце языка Go. Мы посмотрим
// functions with a few different examples. // использование функций на нескольих примерах.
package main package main
import "fmt" import "fmt"
// Here's a function that takes two `int`s and returns // Эта функция принимает в качестве аргументов
// their sum as an `int`. // два целых числа и возвращает их сумму, так
// же с типом целое число.
func plus(a int, b int) int { func plus(a int, b int) int {
// Go requires explicit returns, i.e. it won't // Go требует явного указания типа возвращаемого
// automatically return the value of the last // значение, то есть он не будет автоматически
// expression. // возвращать значение последнего выражения.
return a + b return a + b
} }
// When you have multiple consecutive parameters of // Если функция принимает несколько аргументов с
// the same type, you may omit the type name for the // одинаковым типом, то вы можете перечислить аргументы
// like-typed parameters up to the final parameter that // через запятую и указать тип один раз.
// declares the type.
func plusPlus(a, b, c int) int { func plusPlus(a, b, c int) int {
return a + b + c return a + b + c
} }
func main() { func main() {
// Call a function just as you'd expect, with // Вызов функции осуществялется через запись
// `name(args)`. // `функция(аргументы)`.
res := plus(1, 2) res := plus(1, 2)
fmt.Println("1+2 =", res) fmt.Println("1+2 =", res)

View File

@ -2,5 +2,6 @@ $ go run functions.go
1+2 = 3 1+2 = 3
1+2+3 = 6 1+2+3 = 6
# There are several other features to Go functions. One is # Есть несколько других особенностей для функций в Go.
# multiple return values, which we'll look at next. # Одной из них является возможнсоть возврата нескольких
# значений, которые мы рассмотрим далее.

View File

@ -1,5 +1,5 @@
// Our first program will print the classic "hello world" // Наша первая программа напечатает классическое сообщение "hello world"
// message. Here's the full source code. // Полный код.
package main package main
import "fmt" import "fmt"

View File

@ -1,5 +1,5 @@
// Branching with `if` and `else` in Go is // Условные операторы `if` и` else` в Go
// straight-forward. // выглядят достаточно стандартно
package main package main
@ -7,21 +7,21 @@ import "fmt"
func main() { func main() {
// Here's a basic example. // Стандартное использование
if 7%2 == 0 { if 7%2 == 0 {
fmt.Println("7 is even") fmt.Println("7 is even")
} else { } else {
fmt.Println("7 is odd") fmt.Println("7 is odd")
} }
// You can have an `if` statement without an else. // Вы можете использовать блоке `if` без блока `else`.
if 8%4 == 0 { if 8%4 == 0 {
fmt.Println("8 is divisible by 4") fmt.Println("8 is divisible by 4")
} }
// A statement can precede conditionals; any variables // Присваивание переменной может происходить до условия.
// declared in this statement are available in all // Любые определенные значения будут доступны в
// branches. // последующих ветках
if num := 9; num < 0 { if num := 9; num < 0 {
fmt.Println(num, "is negative") fmt.Println(num, "is negative")
} else if num < 10 { } else if num < 10 {
@ -31,5 +31,5 @@ func main() {
} }
} }
// Note that you don't need parentheses around conditions // Имейте ввиду, что в Go не надо использовать скобки в условии,
// in Go, but that the braces are required. // но блок необходимо заключать в фигурные скобки

View File

@ -1,5 +1,5 @@
// _Maps_ are Go's built-in [associative data type](http://en.wikipedia.org/wiki/Associative_array) // Карты - это встроенный [ассоциативный тип данных](http://en.wikipedia.org/wiki/Associative_array)
// (sometimes called _hashes_ or _dicts_ in other languages). // Go (иногда называемый _хешами_).
package main package main
@ -7,44 +7,44 @@ import "fmt"
func main() { func main() {
// To create an empty map, use the builtin `make`: // Для создания пустой карты, используйте `make`:
// `make(map[key-type]val-type)`. // `make(map[key-type]val-type)`.
m := make(map[string]int) m := make(map[string]int)
// Set key/value pairs using typical `name[key] = val` // Вы можете установить пару ключ/значение
// syntax. // используя привычный синтаксис `name[key] = val`
m["k1"] = 7 m["k1"] = 7
m["k2"] = 13 m["k2"] = 13
// Printing a map with e.g. `fmt.Println` will show all of // Вывод карты на экран с помощью `fmt.Println`
// its key/value pairs. // выведет все пары ключ/значение
fmt.Println("map:", m) fmt.Println("map:", m)
// Get a value for a key with `name[key]`. // Получить значение по ключу `name[key]`.
v1 := m["k1"] v1 := m["k1"]
fmt.Println("v1: ", v1) fmt.Println("v1: ", v1)
// The builtin `len` returns the number of key/value // Встроенная функция `len` возвращает количество
// pairs when called on a map. // пар ключ/значение для карты.
fmt.Println("len:", len(m)) fmt.Println("len:", len(m))
// The builtin `delete` removes key/value pairs from // Встроенная функция `delete` удаляет пару key/value
// a map. // из карты.
delete(m, "k2") delete(m, "k2")
fmt.Println("map:", m) fmt.Println("map:", m)
// The optional second return value when getting a // Необязательное второе возвращаемое значение
// value from a map indicates if the key was present // из карты сообщает о том, существовал ли ключ в карте.
// in the map. This can be used to disambiguate // Это может быть использовано для устранения
// between missing keys and keys with zero values // неоднозначности между отсутствующими ключами и
// like `0` or `""`. Here we didn't need the value // ключами с нулевыми значениями, такими как 0 или
// itself, so we ignored it with the _blank identifier_ // "". Здесь нам не нужно само значение, поэтому
// `_`. // мы проигнорировали его с пустым идентификатором _.
_, prs := m["k2"] _, prs := m["k2"]
fmt.Println("prs:", prs) fmt.Println("prs:", prs)
// You can also declare and initialize a new map in // Вы можете объявить и наполнить карту в одной
// the same line with this syntax. // строке с помощью подобного синтаксиса.
n := map[string]int{"foo": 1, "bar": 2} n := map[string]int{"foo": 1, "bar": 2}
fmt.Println("map:", n) fmt.Println("map:", n)
} }

View File

@ -1,5 +1,5 @@
# Note that maps appear in the form `map[k:v k:v]` when # Обратите внимание, что карты отображаются в виде `map[k:v k:v]`
# printed with `fmt.Println`. # при печати с помощью `fmt.Println`
$ go run maps.go $ go run maps.go
map: map[k1:7 k2:13] map: map[k1:7 k2:13]
v1: 7 v1: 7

View File

@ -1,27 +1,29 @@
// Go has built-in support for _multiple return values_. // Go имеет встроенную поддержку _нескольких возвращаемых
// This feature is used often in idiomatic Go, for example // значений_. Эта особенность часто применяется в Go,
// to return both result and error values from a function. // например, для возврата результата функции и ошибки.
package main package main
import "fmt" import "fmt"
// The `(int, int)` in this function signature shows that // Запись `(int, int)` в описании этой функции, говорит о
// the function returns 2 `int`s. // том, что функция возвращает два целых числа.
func vals() (int, int) { func vals() (int, int) {
return 3, 7 return 3, 7
} }
func main() { func main() {
// Here we use the 2 different return values from the // Здесь функция возвращает два разных значения и
// call with _multiple assignment_. // присваивает их переменным `a,b`. Это называется
// _множественное присваивание_.
a, b := vals() a, b := vals()
fmt.Println(a) fmt.Println(a)
fmt.Println(b) fmt.Println(b)
// If you only want a subset of the returned values, // Если вы хотите получить не все значения, возвращаемые
// use the blank identifier `_`. // функцией, то можно поспользоваться пустым
// идентификатором `_`.
_, c := vals() _, c := vals()
fmt.Println(c) fmt.Println(c)
} }

View File

@ -3,5 +3,6 @@ $ go run multiple-return-values.go
7 7
7 7
# Accepting a variable number of arguments is another nice # Принятие переменного количества аргументов -
# feature of Go functions; we'll look at this next. # еще одна приятная особенность функций Go;
# Рассмотрим это дальше.

View File

@ -1,6 +1,7 @@
// _range_ iterates over elements in a variety of data // _range_ перебирает элементы в различных структурах
// structures. Let's see how to use `range` with some // данных. Давайте посмотрим, как использовать
// of the data structures we've already learned. // `range` с некоторыми из структур данных, которые
// мы уже изучили.
package main package main
@ -8,8 +9,9 @@ import "fmt"
func main() { func main() {
// Here we use `range` to sum the numbers in a slice. // В данном примере мы используем `range` для
// Arrays work like this too. // подсчета суммы чисел в срезе.
// Для массива синтаксис будет такой же.
nums := []int{2, 3, 4} nums := []int{2, 3, 4}
sum := 0 sum := 0
for _, num := range nums { for _, num := range nums {
@ -17,31 +19,31 @@ func main() {
} }
fmt.Println("sum:", sum) fmt.Println("sum:", sum)
// `range` on arrays and slices provides both the // `range` для массивов и срезов возвращает индекс
// index and value for each entry. Above we didn't // и значение для каждого элемента. Если нам не
// need the index, so we ignored it with the // требуется индекс, мы можем использовать оператор
// blank identifier `_`. Sometimes we actually want // `_` для игнорирования. Иногда нам действительно
// the indexes though. // необходимы индексы.
for i, num := range nums { for i, num := range nums {
if num == 3 { if num == 3 {
fmt.Println("index:", i) fmt.Println("index:", i)
} }
} }
// `range` on map iterates over key/value pairs. // `range` для карт перебирает пары ключ/значение.
kvs := map[string]string{"a": "apple", "b": "banana"} kvs := map[string]string{"a": "apple", "b": "banana"}
for k, v := range kvs { for k, v := range kvs {
fmt.Printf("%s -> %s\n", k, v) fmt.Printf("%s -> %s\n", k, v)
} }
// `range` can also iterate over just the keys of a map. // `range` может перебирать только ключи в карте
for k := range kvs { for k := range kvs {
fmt.Println("key:", k) fmt.Println("key:", k)
} }
// `range` on strings iterates over Unicode code // `range` для строк перебирает кодовые точки Unicode.
// points. The first value is the starting byte index // Первое значение - это начальный байтовый индекс
// of the `rune` and the second the `rune` itself. // руны, а второе - сама руна.
for i, c := range "go" { for i, c := range "go" {
fmt.Println(i, c) fmt.Println(i, c)
} }

View File

@ -1,5 +1,6 @@
// _Slices_ are a key data type in Go, giving a more // _Срезы_ являются ключевым типом данных в Go,
// powerful interface to sequences than arrays. // предоставляя более мощный интерфейс для последовательностей,
// чем массивы.
package main package main
@ -7,63 +8,66 @@ import "fmt"
func main() { func main() {
// Unlike arrays, slices are typed only by the // В отличии от массивов, длина среза зависит от содержащихся
// elements they contain (not the number of elements). // в срезе элементов, а не определена при инициализации.
// To create an empty slice with non-zero length, use // Создать пустой срез в ненулевой длиной можно используя
// the builtin `make`. Here we make a slice of // оператор `make`. В этом пример мы создаем слайс строк
// `string`s of length `3` (initially zero-valued). // длиной 3 (заполненный нулевыми значениями).
s := make([]string, 3) s := make([]string, 3)
fmt.Println("emp:", s) fmt.Println("emp:", s)
// We can set and get just like with arrays. // Мы можем устанавливать и получать значения, как в массивах.
s[0] = "a" s[0] = "a"
s[1] = "b" s[1] = "b"
s[2] = "c" s[2] = "c"
fmt.Println("set:", s) fmt.Println("set:", s)
fmt.Println("get:", s[2]) fmt.Println("get:", s[2])
// `len` returns the length of the slice as expected. // `len` возвращает длину среза, как и ожидалось.
fmt.Println("len:", len(s)) fmt.Println("len:", len(s))
// In addition to these basic operations, slices // В дополнение к базовой функциональности, срезы
// support several more that make them richer than // имеют несколько дополнительных особенностей
// arrays. One is the builtin `append`, which // по сравнению с массивыми. Одна из них - `append`,
// returns a slice containing one or more new values. // которая возвращает срезу содержащий одно или более
// Note that we need to accept a return value from // новых значений. Обратите внимание, что результат
// `append` as we may get a new slice value. // функции `append` необходимо присвоить в переменную,
// т.к. это уже будет новый срез.
s = append(s, "d") s = append(s, "d")
s = append(s, "e", "f") s = append(s, "e", "f")
fmt.Println("apd:", s) fmt.Println("apd:", s)
// Slices can also be `copy`'d. Here we create an // Срезы могут быть скопированы с помощью `copy`. В
// empty slice `c` of the same length as `s` and copy // данном примере мы создаем пустой срез `c` такой же
// into `c` from `s`. // длины как и `s` и копируем данные из `s` в `c`.
c := make([]string, len(s)) c := make([]string, len(s))
copy(c, s) copy(c, s)
fmt.Println("cpy:", c) fmt.Println("cpy:", c)
// Slices support a "slice" operator with the syntax // Срезы поддерживают оператор `slice` (синтаксис
// `slice[low:high]`. For example, this gets a slice // использование `slice[low:high]`). Для примера,
// of the elements `s[2]`, `s[3]`, and `s[4]`. // тут мы получаем срез состоящий из элементов
// `s[2]`, `s[3]`, и `s[4]`.
l := s[2:5] l := s[2:5]
fmt.Println("sl1:", l) fmt.Println("sl1:", l)
// This slices up to (but excluding) `s[5]`. // Тут мы получаем срез до элемента `s[5]` (исключая его).
l = s[:5] l = s[:5]
fmt.Println("sl2:", l) fmt.Println("sl2:", l)
// And this slices up from (and including) `s[2]`. // А тут получаем срез от `s[2]` (включая его) и до конца
// исходного среза.
l = s[2:] l = s[2:]
fmt.Println("sl3:", l) fmt.Println("sl3:", l)
// We can declare and initialize a variable for slice // Мы можем объявить и заполнить срез значениями в одну
// in a single line as well. // строку.
t := []string{"g", "h", "i"} t := []string{"g", "h", "i"}
fmt.Println("dcl:", t) fmt.Println("dcl:", t)
// Slices can be composed into multi-dimensional data // Срезы можно объединять в многомерные структуры
// structures. The length of the inner slices can // данных. Длина внутренних срезов может варьироваться,
// vary, unlike with multi-dimensional arrays. // в отличии от многомерных массивов.
twoD := make([][]int, 3) twoD := make([][]int, 3)
for i := 0; i < 3; i++ { for i := 0; i < 3; i++ {
innerLen := i + 1 innerLen := i + 1

View File

@ -1,5 +1,6 @@
# Note that while slices are different types than arrays, # Обратите внимание, несмотря на то что срезы
# they are rendered similarly by `fmt.Println`. # являются отдельным типом данных, отображаются
# они так же как массивы командой `fmt.Println`.
$ go run slices.go $ go run slices.go
emp: [ ] emp: [ ]
set: [a b c] set: [a b c]
@ -13,9 +14,10 @@ sl3: [c d e f]
dcl: [g h i] dcl: [g h i]
2d: [[0] [1 2] [2 3 4]] 2d: [[0] [1 2] [2 3 4]]
# Check out this [great blog post](http://blog.golang.org/2011/01/go-slices-usage-and-internals.html) # Посмотрите этот [отличный пост](http://blog.golang.org/2011/01/go-slices-usage-and-internals.html),
# by the Go team for more details on the design and # написаный командой Go, чтобы узнать больше о разработке
# implementation of slices in Go. # и использовании срезов в Go.
# Now that we've seen arrays and slices we'll look at # Теперь, когда мы рассмотрели массивы и срезы, мы
# Go's other key builtin data structure: maps. # посмотрим другую ключевую встроенную структуру
# данных Go: карты.

View File

@ -1,5 +1,4 @@
// _Switch statements_ express conditionals across many // _Switch_ помогает проверять условие в нескольких блоках
// branches.
package main package main
@ -10,7 +9,7 @@ import (
func main() { func main() {
// Here's a basic `switch`. // Стандартное использование `switch`.
i := 2 i := 2
fmt.Print("Write ", i, " as ") fmt.Print("Write ", i, " as ")
switch i { switch i {
@ -22,9 +21,10 @@ func main() {
fmt.Println("three") fmt.Println("three")
} }
// You can use commas to separate multiple expressions // Вы можете использовать запятую в качестве разделителя,
// in the same `case` statement. We use the optional // для перечисления нескольких значений в `case`.
// `default` case in this example as well. // Так же в данном примере используется блок
// по-умолчанию `default`.
switch time.Now().Weekday() { switch time.Now().Weekday() {
case time.Saturday, time.Sunday: case time.Saturday, time.Sunday:
fmt.Println("It's the weekend") fmt.Println("It's the weekend")
@ -32,9 +32,9 @@ func main() {
fmt.Println("It's a weekday") fmt.Println("It's a weekday")
} }
// `switch` without an expression is an alternate way // `switch` без условия аналогичен обычному оператору
// to express if/else logic. Here we also show how the // `if/else` по своей логике. Так же в этом примере
// `case` expressions can be non-constants. // что в `case` можно использовать не только константы.
t := time.Now() t := time.Now()
switch { switch {
case t.Hour() < 12: case t.Hour() < 12:
@ -43,10 +43,9 @@ func main() {
fmt.Println("It's after noon") fmt.Println("It's after noon")
} }
// A type `switch` compares types instead of values. You // В этой конструкции `switch` сравниваются типы значений.
// can use this to discover the type of an interface // Вы можете использовать этот прием, для определения
// value. In this example, the variable `t` will have the // типа значения интерфейса.
// type corresponding to its clause.
whatAmI := func(i interface{}) { whatAmI := func(i interface{}) {
switch t := i.(type) { switch t := i.(type) {
case bool: case bool:

View File

@ -1,6 +1,6 @@
// Go has various value types including strings, // В Go существуют различные типы значений: строки,
// integers, floats, booleans, etc. Here are a few // целые числа, числа с плавающей точкой, булевы и т.д.
// basic examples. // Вот некоторые примеры
package main package main
@ -8,14 +8,14 @@ import "fmt"
func main() { func main() {
// Strings, which can be added together with `+`. // Строки могут быть сложены с помощью символа `+`.
fmt.Println("go" + "lang") fmt.Println("go" + "lang")
// Integers and floats. // Целый числа и числа с плавающей точкой.
fmt.Println("1+1 =", 1+1) fmt.Println("1+1 =", 1+1)
fmt.Println("7.0/3.0 =", 7.0/3.0) fmt.Println("7.0/3.0 =", 7.0/3.0)
// Booleans, with boolean operators as you'd expect. // Логические значения с логическими операторами
fmt.Println(true && false) fmt.Println(true && false)
fmt.Println(true || false) fmt.Println(true || false)
fmt.Println(!true) fmt.Println(!true)

View File

@ -1,6 +1,6 @@
// In Go, _variables_ are explicitly declared and used by // В Go, _переменные_ объявляются явно и используются
// the compiler to e.g. check type-correctness of function // компилятором, например, для проверки корректного
// calls. // вызова функции (типы аргументов)
package main package main
@ -8,27 +8,28 @@ import "fmt"
func main() { func main() {
// `var` declares 1 or more variables. // `var` объявляет 1 или более переменных
var a = "initial" var a = "initial"
fmt.Println(a) fmt.Println(a)
// You can declare multiple variables at once. // Вы можете объявить несколько переменных за раз
var b, c int = 1, 2 var b, c int = 1, 2
fmt.Println(b, c) fmt.Println(b, c)
// Go will infer the type of initialized variables. // Go будет определять тип по инициализированной переменной.
var d = true var d = true
fmt.Println(d) fmt.Println(d)
// Variables declared without a corresponding // Переменные, объявленные без соответствующей инициализации,
// initialization are _zero-valued_. For example, the // имеют _нулевое значение_. Например, нулевое значение
// zero value for an `int` is `0`. // для `int` равно `0`.
var e int var e int
fmt.Println(e) fmt.Println(e)
// The `:=` syntax is shorthand for declaring and // В Go существует короткий пператор `:=` для
// initializing a variable, e.g. for // объявления и инициализации переменной.
// `var f string = "apple"` in this case. // Например, `var f string = "apple"` в короткой записи
// превратится в
f := "apple" f := "apple"
fmt.Println(f) fmt.Println(f)
} }

View File

@ -1,14 +1,13 @@
// [_Variadic functions_](http://en.wikipedia.org/wiki/Variadic_function) // [_Функции с переменным числом аргументов_](http://en.wikipedia.org/wiki/Variadic_function)
// can be called with any number of trailing arguments. // могут быть вызваны с любым количество аргументов.
// For example, `fmt.Println` is a common variadic // Пример такой функции - это `fmt.Println`.
// function.
package main package main
import "fmt" import "fmt"
// Here's a function that will take an arbitrary number // Это функция, которая может принимать любое количество
// of `int`s as arguments. // аргументов целых чисел.
func sum(nums ...int) { func sum(nums ...int) {
fmt.Print(nums, " ") fmt.Print(nums, " ")
total := 0 total := 0
@ -20,14 +19,13 @@ func sum(nums ...int) {
func main() { func main() {
// Variadic functions can be called in the usual way // Такие функции можно вызывать обычным способом.
// with individual arguments.
sum(1, 2) sum(1, 2)
sum(1, 2, 3) sum(1, 2, 3)
// If you already have multiple args in a slice, // Если у вас есть несколько аргументов в срезе,
// apply them to a variadic function using // вы можете применить его к функции с переменным
// `func(slice...)` like this. // числом аргументов таким образом `func(slice...)`.
nums := []int{1, 2, 3, 4} nums := []int{1, 2, 3, 4}
sum(nums...) sum(nums...)
} }

View File

@ -3,5 +3,5 @@ $ go run variadic-functions.go
[1 2 3] 6 [1 2 3] 6
[1 2 3 4] 10 [1 2 3 4] 10
# Another key aspect of functions in Go is their ability # Другим ключевым аспектом функций в Go являются
# to form closures, which we'll look at next. # замыкания, которые мы рассмотрим далее.