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
Content and build toolchain for [Go by Example](https://gobyexample.com),
a site that teaches Go via annotated example programs.
Набор инструментов для генерации [Go в примерах](https://gobyexample.su),
сайта который помогает изучать язык Go на примерах.
### Overview
### Обзор
The Go by Example site is built by extracting code and
comments from source files in `examples` and rendering
them via the `templates` into a static `public`
directory. The programs implementing this build process
are in `tools`, along with some vendor'd dependencies
in `vendor`.
Сайт **Go в Примерах** генерируется на основании кода и комментариев
в файлах в папке `examples` и рендерится на основании шаблонов в папке
`templates`. Готовый сайт находится в `public`.
Программы, реализующие процесс сборки находятся в `tools`,
вместе с некоторыми вендорными зависимостями в `vendor`.
The built `public` directory can be served by any
static content system. The production site uses S3 and
CloudFront, for example.
### Building
[![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
$ go get github.com/russross/blackfriday
@ -28,15 +24,15 @@ $ tools/build
$ open public/index.html
```
To build continuously in a loop:
Непрерывное построение в цикле:
```console
$ tools/build-loop
```
### Publishing
### Публикация
To upload the site:
Загрузка сайта (AWS):
```console
$ gem install aws-sdk
@ -45,18 +41,18 @@ $ export AWS_SECRET_ACCESS_KEY=...
$ 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/).
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/).
### 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)
* [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)
* [Japanese](http://spinute.org/go-by-example) by [spinute](https://github.com/spinute)
* [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)
* [Ukrainian](http://gobyexample.com.ua/) by [butuzov](https://github.com/butuzov/gobyexample)

View File

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

View File

@ -1,5 +1,5 @@
// In Go, an _array_ is a numbered sequence of elements of a
// specific length.
// В Go, _массив_ это числовой ряд элементов определенной
// длины.
package main
@ -7,31 +7,32 @@ import "fmt"
func main() {
// Here we create an array `a` that will hold exactly
// 5 `int`s. The type of elements and length are both
// part of the array's type. By default an array is
// zero-valued, which for `int`s means `0`s.
// В данном примере мы создаем массив `a`, который
// содержит 5 элементов с типом `int`. Тип элементов
// и длина являются частью типа массива. По-умолчанию
// массив заполняется нулевыми значениями, например,
// в случае `int` нулевое значение - 0.
var a [5]int
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]`.
// Мы можем установить значение по индексу элемента
// следующим образом:`array[index] = value`.
// Получить значение можно аналогично - `array[index]`.
a[4] = 100
fmt.Println("set:", a)
fmt.Println("get:", a[4])
// The builtin `len` returns the length of an array.
// Встроенная функция `len` возвращает длину массива.
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}
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
for i := 0; i < 2; i++ {
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
emp: [0 0 0 0 0]
set: [0 0 0 0 100]
@ -8,5 +8,5 @@ len: 5
dcl: [1 2 3 4 5]
2d: [[0 1 2] [1 2 3]]
# You'll see _slices_ much more often than arrays in
# typical Go. We'll look at slices next.
# В Go вы будете встречать _срезы_ гораздо чаще, чем
# массивы. Срезы рассмотрим далее

View File

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

View File

@ -4,5 +4,5 @@ $ go run closures.go
3
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,
// and numeric values.
// В Go _константы_ могут принимать значения следующих типов:
// строки, числа и логические значения
package main
@ -8,28 +8,28 @@ import (
"math"
)
// `const` declares a constant value.
// Для объявления константы используется ключевое слово `const`.
const s string = "constant"
func main() {
fmt.Println(s)
// A `const` statement can appear anywhere a `var`
// statement can.
// Оператор `const` может использоваться везде, где может
// быть использован оператор `var`.
const n = 500000000
// Constant expressions perform arithmetic with
// arbitrary precision.
// Постоянные выражения выполняют арифметику с
// произвольной точностью.
const d = 3e20 / n
fmt.Println(d)
// A numeric constant has no type until it's given
// one, such as by an explicit conversion.
// Числовая константа не имеет типа до тех пор,
// пока ей не присвоен, например, при явном преобразовании.
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` expects a `float64`.
// Число может использоваться в контексте, который требует
// его, например, присваивание переменной или вызов
// функции. Например, здесь `math.Sin` ожидает
// `float64`.
fmt.Println(math.Sin(n))
}

View File

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

View File

@ -1,32 +1,32 @@
// _Functions_ are central in Go. We'll learn about
// functions with a few different examples.
// _Функции_ это сердце языка Go. Мы посмотрим
// использование функций на нескольих примерах.
package main
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 {
// Go requires explicit returns, i.e. it won't
// automatically return the value of the last
// expression.
// Go требует явного указания типа возвращаемого
// значение, то есть он не будет автоматически
// возвращать значение последнего выражения.
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 {
return a + b + c
}
func main() {
// Call a function just as you'd expect, with
// `name(args)`.
// Вызов функции осуществялется через запись
// `функция(аргументы)`.
res := plus(1, 2)
fmt.Println("1+2 =", res)

View File

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

View File

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

View File

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

View File

@ -1,5 +1,5 @@
// _Maps_ are Go's built-in [associative data type](http://en.wikipedia.org/wiki/Associative_array)
// (sometimes called _hashes_ or _dicts_ in other languages).
// Карты - это встроенный [ассоциативный тип данных](http://en.wikipedia.org/wiki/Associative_array)
// Go (иногда называемый _хешами_).
package main
@ -7,44 +7,44 @@ import "fmt"
func main() {
// To create an empty map, use the builtin `make`:
// Для создания пустой карты, используйте `make`:
// `make(map[key-type]val-type)`.
m := make(map[string]int)
// Set key/value pairs using typical `name[key] = val`
// syntax.
// Вы можете установить пару ключ/значение
// используя привычный синтаксис `name[key] = val`
m["k1"] = 7
m["k2"] = 13
// Printing a map with e.g. `fmt.Println` will show all of
// its key/value pairs.
// Вывод карты на экран с помощью `fmt.Println`
// выведет все пары ключ/значение
fmt.Println("map:", m)
// Get a value for a key with `name[key]`.
// Получить значение по ключу `name[key]`.
v1 := m["k1"]
fmt.Println("v1: ", v1)
// The builtin `len` returns the number of key/value
// pairs when called on a map.
// Встроенная функция `len` возвращает количество
// пар ключ/значение для карты.
fmt.Println("len:", len(m))
// The builtin `delete` removes key/value pairs from
// a map.
// Встроенная функция `delete` удаляет пару key/value
// из карты.
delete(m, "k2")
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
// itself, so we ignored it with the _blank identifier_
// `_`.
// Необязательное второе возвращаемое значение
// из карты сообщает о том, существовал ли ключ в карте.
// Это может быть использовано для устранения
// неоднозначности между отсутствующими ключами и
// ключами с нулевыми значениями, такими как 0 или
// "". Здесь нам не нужно само значение, поэтому
// мы проигнорировали его с пустым идентификатором _.
_, prs := m["k2"]
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}
fmt.Println("map:", n)
}

View File

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

View File

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

View File

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

View File

@ -1,5 +1,6 @@
// _Slices_ are a key data type in Go, giving a more
// powerful interface to sequences than arrays.
// _Срезы_ являются ключевым типом данных в Go,
// предоставляя более мощный интерфейс для последовательностей,
// чем массивы.
package main
@ -7,63 +8,66 @@ import "fmt"
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
// `string`s of length `3` (initially zero-valued).
// В отличии от массивов, длина среза зависит от содержащихся
// в срезе элементов, а не определена при инициализации.
// Создать пустой срез в ненулевой длиной можно используя
// оператор `make`. В этом пример мы создаем слайс строк
// длиной 3 (заполненный нулевыми значениями).
s := make([]string, 3)
fmt.Println("emp:", s)
// We can set and get just like with arrays.
// Мы можем устанавливать и получать значения, как в массивах.
s[0] = "a"
s[1] = "b"
s[2] = "c"
fmt.Println("set:", s)
fmt.Println("get:", s[2])
// `len` returns the length of the slice as expected.
// `len` возвращает длину среза, как и ожидалось.
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
// 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`,
// которая возвращает срезу содержащий одно или более
// новых значений. Обратите внимание, что результат
// функции `append` необходимо присвоить в переменную,
// т.к. это уже будет новый срез.
s = append(s, "d")
s = append(s, "e", "f")
fmt.Println("apd:", s)
// Slices can also be `copy`'d. Here we create an
// empty slice `c` of the same length as `s` and copy
// into `c` from `s`.
// Срезы могут быть скопированы с помощью `copy`. В
// данном примере мы создаем пустой срез `c` такой же
// длины как и `s` и копируем данные из `s` в `c`.
c := make([]string, len(s))
copy(c, s)
fmt.Println("cpy:", c)
// Slices support a "slice" operator with the syntax
// `slice[low:high]`. For example, this gets a slice
// of the elements `s[2]`, `s[3]`, and `s[4]`.
// Срезы поддерживают оператор `slice` (синтаксис
// использование `slice[low:high]`). Для примера,
// тут мы получаем срез состоящий из элементов
// `s[2]`, `s[3]`, и `s[4]`.
l := s[2:5]
fmt.Println("sl1:", l)
// This slices up to (but excluding) `s[5]`.
// Тут мы получаем срез до элемента `s[5]` (исключая его).
l = s[:5]
fmt.Println("sl2:", l)
// And this slices up from (and including) `s[2]`.
// А тут получаем срез от `s[2]` (включая его) и до конца
// исходного среза.
l = s[2:]
fmt.Println("sl3:", l)
// We can declare and initialize a variable for slice
// in a single line as well.
// Мы можем объявить и заполнить срез значениями в одну
// строку.
t := []string{"g", "h", "i"}
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)
for i := 0; i < 3; i++ {
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
emp: [ ]
set: [a b c]
@ -13,9 +14,10 @@ sl3: [c d e f]
dcl: [g h i]
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)
# by the Go team for more details on the design and
# implementation of slices in Go.
# Посмотрите этот [отличный пост](http://blog.golang.org/2011/01/go-slices-usage-and-internals.html),
# написаный командой 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
// branches.
// _Switch_ помогает проверять условие в нескольких блоках
package main
@ -10,7 +9,7 @@ import (
func main() {
// Here's a basic `switch`.
// Стандартное использование `switch`.
i := 2
fmt.Print("Write ", i, " as ")
switch i {
@ -22,9 +21,10 @@ func main() {
fmt.Println("three")
}
// You can use commas to separate multiple expressions
// in the same `case` statement. We use the optional
// `default` case in this example as well.
// Вы можете использовать запятую в качестве разделителя,
// для перечисления нескольких значений в `case`.
// Так же в данном примере используется блок
// по-умолчанию `default`.
switch time.Now().Weekday() {
case time.Saturday, time.Sunday:
fmt.Println("It's the weekend")
@ -32,9 +32,9 @@ func main() {
fmt.Println("It's a weekday")
}
// `switch` without an expression is an alternate way
// to express if/else logic. Here we also show how the
// `case` expressions can be non-constants.
// `switch` без условия аналогичен обычному оператору
// `if/else` по своей логике. Так же в этом примере
// что в `case` можно использовать не только константы.
t := time.Now()
switch {
case t.Hour() < 12:
@ -43,10 +43,9 @@ func main() {
fmt.Println("It's after noon")
}
// A type `switch` compares types instead of values. You
// 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.
// В этой конструкции `switch` сравниваются типы значений.
// Вы можете использовать этот прием, для определения
// типа значения интерфейса.
whatAmI := func(i interface{}) {
switch t := i.(type) {
case bool:

View File

@ -1,6 +1,6 @@
// Go has various value types including strings,
// integers, floats, booleans, etc. Here are a few
// basic examples.
// В Go существуют различные типы значений: строки,
// целые числа, числа с плавающей точкой, булевы и т.д.
// Вот некоторые примеры
package main
@ -8,14 +8,14 @@ import "fmt"
func main() {
// Strings, which can be added together with `+`.
// Строки могут быть сложены с помощью символа `+`.
fmt.Println("go" + "lang")
// Integers and floats.
// Целый числа и числа с плавающей точкой.
fmt.Println("1+1 =", 1+1)
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)

View File

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

View File

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

View File

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