In Go, an array is a numbered sequence of elements of a
-specific length.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
packagemain
-
-
-
-
-
-
-
-
-
-
-
-
import"fmt"
-
-
-
-
-
-
-
-
-
-
-
-
funcmain(){
-
-
-
-
-
-
-
-
Here we create an array a that will hold exactly
-5 ints. The type of elements and length are both
-part of the array’s type. By default an array is
-zero-valued, which for ints means 0s.
-
-
-
-
-
vara[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].
The primary mechanism for managing state in Go is
-communication over channels. We saw this for example
-with worker pools. There are a few other
-options for managing state though. Here we’ll
-look at using the sync/atomic package for atomic
-counters accessed by multiple goroutines.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
packagemain
-
-
-
-
-
-
-
-
-
-
-
-
import(
- "fmt"
- "sync"
- "sync/atomic"
-)
-
-
-
-
-
-
-
-
-
-
-
-
funcmain(){
-
-
-
-
-
-
-
-
We’ll use an unsigned integer to represent our
-(always-positive) counter.
-
-
-
-
-
varopsuint64
-
-
-
-
-
-
-
-
A WaitGroup will help us wait for all goroutines
-to finish their work.
-
-
-
-
-
varwgsync.WaitGroup
-
-
-
-
-
-
-
-
We’ll start 50 goroutines that each increment the
-counter exactly 1000 times.
-
-
-
-
-
fori:=0;i<50;i++{
- wg.Add(1)
-
-
-
-
-
-
-
-
To atomically increment the counter we
-use AddUint64, giving it the memory
-address of our ops counter with the
-& syntax.
It’s safe to access ops now because we know
-no other goroutine is writing to it. Reading
-atomics safely while they are being updated is
-also possible, using functions like
-atomic.LoadUint64.
-
-
-
-
-
fmt.Println("ops:",ops)
-}
-
-
-
-
-
-
-
-
-
-
-
-
We expect to get exactly 50,000 operations. Had we
-used the non-atomic ops++ to increment the counter,
-we’d likely get a different number, changing between
-runs, because the goroutines would interfere with
-each other. Moreover, we’d get data race failures
-when running with the -race flag.
-
-
-
-
-
$ go run atomic-counters.go
-ops: 50000
-
-
-
-
-
-
-
-
Next we’ll look at mutexes, another tool for managing
-state.
This syntax imports the encoding/base64 package with
-the b64 name instead of the default base64. It’ll
-save us some space below.
-
-
-
-
-
import(
- b64"encoding/base64"
- "fmt"
-)
-
-
-
-
-
-
-
-
-
-
-
-
funcmain(){
-
-
-
-
-
-
-
-
Here’s the string we’ll encode/decode.
-
-
-
-
-
data:="abc123!?$*&()'-=@~"
-
-
-
-
-
-
-
-
Go supports both standard and URL-compatible
-base64. Here’s how to encode using the standard
-encoder. The encoder requires a []byte so we
-convert our string to that type.
The string encodes to slightly different values with the
-standard and URL base64 encoders (trailing + vs -)
-but they both decode to the original string as desired.
-
-
-
-
-
$ go run base64-encoding.go
-YWJjMTIzIT8kKiYoKSctPUB+
-abc123!?$*&()'-=@~
-
By default channels are unbuffered, meaning that they
-will only accept sends (chan <-) if there is a
-corresponding receive (<- chan) ready to receive the
-sent value. Buffered channels accept a limited
-number of values without a corresponding receiver for
-those values.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
packagemain
-
-
-
-
-
-
-
-
-
-
-
-
import"fmt"
-
-
-
-
-
-
-
-
-
-
-
-
funcmain(){
-
-
-
-
-
-
-
-
Here we make a channel of strings buffering up to
-2 values.
-
-
-
-
-
messages:=make(chanstring,2)
-
-
-
-
-
-
-
-
Because this channel is buffered, we can send these
-values into the channel without a corresponding
-concurrent receive.
diff --git a/public/channel-directions b/public/channel-directions
index fbbe7b5..f50b677 100644
--- a/public/channel-directions
+++ b/public/channel-directions
@@ -2,7 +2,7 @@
- Go by Example: Channel Directions
+ Go в примерах: Направления канала (Channel Directions)
When using channels as function parameters, you can
-specify if a channel is meant to only send or receive
-values. This specificity increases the type-safety of
-the program.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
packagemain
-
-
-
-
-
-
-
-
-
-
-
-
import"fmt"
-
-
-
-
-
-
-
-
This ping function only accepts a channel for sending
-values. It would be a compile-time error to try to
-receive on this channel.
Go в примерах: Направления канала (Channel Directions)
- Next example: Select.
+ Следующий пример: Select.
@@ -145,7 +34,7 @@ receive on this channel.
diff --git a/public/channel-synchronization b/public/channel-synchronization
index 7a0d3a3..b421afc 100644
--- a/public/channel-synchronization
+++ b/public/channel-synchronization
@@ -2,7 +2,7 @@
- Go by Example: Channel Synchronization
+ Go в примерах: Синхронизация канала (Channel Synchronization)
We can use channels to synchronize execution
-across goroutines. Here’s an example of using a
-blocking receive to wait for a goroutine to finish.
-When waiting for multiple goroutines to finish,
-you may prefer to use a WaitGroup.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
packagemain
-
-
-
-
-
-
-
-
-
-
-
-
import(
- "fmt"
- "time"
-)
-
-
-
-
-
-
-
-
This is the function we’ll run in a goroutine. The
-done channel will be used to notify another
-goroutine that this function’s work is done.
Channels are the pipes that connect concurrent
-goroutines. You can send values into channels from one
-goroutine and receive those values into another
-goroutine.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
packagemain
-
-
-
-
-
-
-
-
-
-
-
-
import"fmt"
-
-
-
-
-
-
-
-
-
-
-
-
funcmain(){
-
-
-
-
-
-
-
-
Create a new channel with make(chan val-type).
-Channels are typed by the values they convey.
-
-
-
-
-
messages:=make(chanstring)
-
-
-
-
-
-
-
-
Send a value into a channel using the channel <-
-syntax. Here we send "ping" to the messages
-channel we made above, from a new goroutine.
-
-
-
-
-
gofunc(){messages<-"ping"}()
-
-
-
-
-
-
-
-
The <-channel syntax receives a value from the
-channel. Here we’ll receive the "ping" message
-we sent above and print it out.
-
-
-
-
-
msg:=<-messages
- fmt.Println(msg)
-}
-
-
-
-
-
-
-
-
-
-
-
-
When we run the program the "ping" message is
-successfully passed from one goroutine to another via
-our channel.
-
-
-
-
-
$ go run channels.go
-ping
-
-
-
-
-
-
-
-
By default sends and receives block until both the
-sender and receiver are ready. This property allowed
-us to wait at the end of our program for the "ping"
-message without having to use any other synchronization.
Closing a channel indicates that no more values
-will be sent on it. This can be useful to communicate
-completion to the channel’s receivers.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
packagemain
-
-
-
-
-
-
-
-
-
-
-
-
import"fmt"
-
-
-
-
-
-
-
-
In this example we’ll use a jobs channel to
-communicate work to be done from the main() goroutine
-to a worker goroutine. When we have no more jobs for
-the worker we’ll close the jobs channel.
Here’s the worker goroutine. It repeatedly receives
-from jobs with j, more := <-jobs. In this
-special 2-value form of receive, the more value
-will be false if jobs has been closed and all
-values in the channel have already been received.
-We use this to notify on done when we’ve worked
-all our jobs.
Go supports anonymous functions,
-which can form closures.
-Anonymous functions are useful when you want to define
-a function inline without having to name it.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
packagemain
-
-
-
-
-
-
-
-
-
-
-
-
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.
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.
-
-
-
-
-
nextInt:=intSeq()
-
-
-
-
-
-
-
-
See the effect of the closure by calling nextInt
-a few times.
diff --git a/public/collection-functions b/public/collection-functions
index 569c4b3..9efcde8 100644
--- a/public/collection-functions
+++ b/public/collection-functions
@@ -2,7 +2,7 @@
- Go by Example: Collection Functions
+ Go в примерах: Функции коллекции (Collection Functions)
We often need our programs to perform operations on
-collections of data, like selecting all items that
-satisfy a given predicate or mapping all items to a new
-collection with a custom function.
-
-
-
-
-
-
-
-
-
-
-
In some languages it’s idiomatic to use generic
-data structures and algorithms. Go does not support
-generics; in Go it’s common to provide collection
-functions if and when they are specifically needed for
-your program and data types.
-
-
-
-
-
-
-
-
-
-
-
Here are some example collection functions for slices
-of strings. You can use these examples to build your
-own functions. Note that in some cases it may be
-clearest to just inline the collection-manipulating
-code directly, instead of creating and calling a
-helper function.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
packagemain
-
-
-
-
-
-
-
-
-
-
-
-
import(
- "fmt"
- "strings"
-)
-
-
-
-
-
-
-
-
Index returns the first index of the target string t, or
--1 if no match is found.
Command-line arguments
-are a common way to parameterize execution of programs.
-For example, go run hello.go uses run and
-hello.go arguments to the go program.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
packagemain
-
-
-
-
-
-
-
-
-
-
-
-
import(
- "fmt"
- "os"
-)
-
-
-
-
-
-
-
-
-
-
-
-
funcmain(){
-
-
-
-
-
-
-
-
os.Args provides access to raw command-line
-arguments. Note that the first value in this slice
-is the path to the program, and os.Args[1:]
-holds the arguments to the program.
Command-line flags
-are a common way to specify options for command-line
-programs. For example, in wc -l the -l is a
-command-line flag.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
packagemain
-
-
-
-
-
-
-
-
Go provides a flag package supporting basic
-command-line flag parsing. We’ll use this package to
-implement our example command-line program.
-
-
-
-
-
import(
- "flag"
- "fmt"
-)
-
-
-
-
-
-
-
-
-
-
-
-
funcmain(){
-
-
-
-
-
-
-
-
Basic flag declarations are available for string,
-integer, and boolean options. Here we declare a
-string flag word with a default value "foo"
-and a short description. This flag.String function
-returns a string pointer (not a string value);
-we’ll see how to use this pointer below.
-
-
-
-
-
wordPtr:=flag.String("word","foo","a string")
-
-
-
-
-
-
-
-
This declares numb and fork flags, using a
-similar approach to the word flag.
It’s also possible to declare an option that uses an
-existing var declared elsewhere in the program.
-Note that we need to pass in a pointer to the flag
-declaration function.
Once all flags are declared, call flag.Parse()
-to execute the command-line parsing.
-
-
-
-
-
flag.Parse()
-
-
-
-
-
-
-
-
Here we’ll just dump out the parsed options and
-any trailing positional arguments. Note that we
-need to dereference the pointers with e.g. *wordPtr
-to get the actual option values.
Note that the flag package requires all flags to
-appear before positional arguments (otherwise the flags
-will be interpreted as positional arguments).
Use -h or --help flags to get automatically
-generated help text for the command-line program.
-
-
-
-
-
$ ./command-line-flags -h
-Usage of ./command-line-flags:
- -fork=false: a bool
- -numb=42: an int
- -svar="bar": a string var
- -word="foo": a string
-
-
-
-
-
-
-
-
If you provide a flag that wasn’t specified to the
-flag package, the program will print an error message
-and show the help text again.
-
-
-
-
-
$ ./command-line-flags -wat
-flag provided but not defined: -wat
-Usage of ./command-line-flags:
-...
-
-
-
-
-
-
+
Go в примерах: Флаги командной строки (Command-Line Flags)
Some command-line tools, like the go tool or git
-have many subcommands, each with its own set of
-flags. For example, go build and go get are two
-different subcommands of the go tool.
-The flag package lets us easily define simple
-subcommands that have their own flags.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
packagemain
-
-
-
-
-
-
-
-
-
-
-
-
import(
- "flag"
- "fmt"
- "os"
-)
-
-
-
-
-
-
-
-
-
-
-
-
funcmain(){
-
-
-
-
-
-
-
-
We declare a subcommand using the NewFlagSet
-function, and proceed to define new flags specific
-for this subcommand.
Go supports constants of character, string, boolean,
-and numeric values.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
packagemain
-
-
-
-
-
-
-
-
-
-
-
-
import(
- "fmt"
- "math"
-)
-
-
-
-
-
-
-
-
const declares a constant value.
-
-
-
-
-
constsstring="constant"
-
-
-
-
-
-
-
-
-
-
-
-
funcmain(){
- fmt.Println(s)
-
-
-
-
-
-
-
-
A const statement can appear anywhere a var
-statement can.
-
-
-
-
-
constn=500000000
-
-
-
-
-
-
-
-
Constant expressions perform arithmetic with
-arbitrary precision.
-
-
-
-
-
constd=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.
-
-
-
-
-
fmt.Println(math.Sin(n))
-}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
$ go run constant.go
-constant
-6e+11
-600000000000
--0.28470407323754404
-
- Next example: For.
+ Следующий пример: Цикл For.
@@ -183,7 +34,7 @@ assignment or function call. For example, here
diff --git a/public/defer b/public/defer
index f99d59d..2beb109 100644
--- a/public/defer
+++ b/public/defer
@@ -2,7 +2,7 @@
- Go by Example: Defer
+ Go в примерах: Defer
Defer is used to ensure that a function call is
-performed later in a program’s execution, usually for
-purposes of cleanup. defer is often used where e.g.
-ensure and finally would be used in other languages.
+
Defer используется, чтобы гарантировать, что
+вызов функции будет выполнен позже при выполнении
+программы, обычно для целей очистки. defer часто
+используется там, где в других языках используются
+ensure и finally.
@@ -44,7 +45,7 @@ purposes of cleanup. defer is often used where e.g.
-
+
packagemain
@@ -68,9 +69,9 @@ purposes of cleanup. defer is often used where e.g.
-
Suppose we wanted to create a file, write to it,
-and then close when we’re done. Here’s how we could
-do that with defer.
+
Предположим, мы хотим создать файл, записать в него,
+а затем закрыть, когда закончим. Вот как нам поможет
+defer.
@@ -83,11 +84,11 @@ do that with defer.
-
Immediately after getting a file object with
-createFile, we defer the closing of that file
-with closeFile. This will be executed at the end
-of the enclosing function (main), after
-writeFile has finished.
+
Сразу же после получения объекта файла с помощью
+createFile мы откладываем закрытие этого файла
+с помощью closeFile. Она будет выполнена в
+конце включающей функции (main) после завершения
+writeFile.
@@ -148,8 +149,8 @@ of the enclosing function (main), after
-
It’s important to check for errors when closing a
-file, even in a deferred function.
+
Важно проверять наличие ошибок при закрытии файла,
+даже в отложенной функции.
@@ -184,8 +185,8 @@ file, even in a deferred function.
-
Running the program confirms that the file is closed
-after being written.
+
Запуск программы подтверждает, что файл закрыт
+после записи.
Create a new sub-directory in the current working
-directory.
-
-
-
-
-
err:=os.Mkdir("subdir",0755)
- check(err)
-
-
-
-
-
-
-
-
When creating temporary directories, it’s good
-practice to defer their removal. os.RemoveAll
-will delete a whole directory tree (similarly to
-rm -rf).
We can also visit a directory recursively,
-including all its sub-directories. Walk accepts
-a callback function to handle every file or
-directory visited.
diff --git a/public/environment-variables b/public/environment-variables
index 25504ae..c08bf0e 100644
--- a/public/environment-variables
+++ b/public/environment-variables
@@ -2,7 +2,7 @@
- Go by Example: Environment Variables
+ Go в примерах: Переменные среды (Environment Variables)
To set a key/value pair, use os.Setenv. To get a
-value for a key, use os.Getenv. This will return
-an empty string if the key isn’t present in the
-environment.
Use os.Environ to list all key/value pairs in the
-environment. This returns a slice of strings in the
-form KEY=value. You can strings.Split them to
-get the key and value. Here we print all the keys.
diff --git a/public/epoch b/public/epoch
index 76a9b20..ddd321a 100644
--- a/public/epoch
+++ b/public/epoch
@@ -2,7 +2,7 @@
- Go by Example: Epoch
+ Go в примерах: Epoch
A common requirement in programs is getting the number
-of seconds, milliseconds, or nanoseconds since the
-Unix epoch.
-Here’s how to do it in Go.
+
Общим требованием в программах является получение
+количества секунд, миллисекунд или наносекунд в Unixtime.
+Вот как это сделать в Go.
@@ -44,7 +43,7 @@ Here’s how to do it in Go.
-
+
packagemain
@@ -80,9 +79,9 @@ Here’s how to do it in Go.
-
Use time.Now with Unix or UnixNano to get
-elapsed time since the Unix epoch in seconds or
-nanoseconds, respectively.
+
Используйте time.Now с Unix или UnixNano,
+чтобы получить время, прошедшее с начала эпохи Unix в
+секундах или наносекундах соответственно.
@@ -98,9 +97,9 @@ nanoseconds, respectively.
-
Note that there is no UnixMillis, so to get the
-milliseconds since epoch you’ll need to manually
-divide from nanoseconds.
+
Обратите внимание, что UnixMillis не существует,
+поэтому, чтобы получить миллисекунды с начала эпохи Unix,
+вам нужно будет вручную делить наносекунды.
@@ -116,8 +115,8 @@ divide from nanoseconds.
-
You can also convert integer seconds or nanoseconds
-since the epoch into the corresponding time.
+
Вы также можете конвертировать целые секунды или наносекунды
+Unixtime в соответствующее время.
@@ -154,8 +153,8 @@ since the epoch into the corresponding time.
-
Next we’ll look at another time-related task: time
-parsing and formatting.
+
Далее мы рассмотрим еще одну задачу, связанную со
+временем: разбор и форматирование времени.
In Go it’s idiomatic to communicate errors via an
-explicit, separate return value. This contrasts with
-the exceptions used in languages like Java and Ruby and
-the overloaded single result / error value sometimes
-used in C. Go’s approach makes it easy to see which
-functions return errors and to handle them using the
-same language constructs employed for any other,
-non-error tasks.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
packagemain
-
-
-
-
-
-
-
-
-
-
-
-
import(
- "errors"
- "fmt"
-)
-
-
-
-
-
-
-
-
By convention, errors are the last return value and
-have type error, a built-in interface.
-
-
-
-
-
funcf1(argint)(int,error){
- ifarg==42{
-
-
-
-
-
-
-
-
errors.New constructs a basic error value
-with the given error message.
-
-
-
-
-
return-1,errors.New("can't work with 42")
-
-
-
-
-
-
-
-
-
-
-
-
}
-
-
-
-
-
-
-
-
A nil value in the error position indicates that
-there was no error.
-
-
-
-
-
returnarg+3,nil
-}
-
-
-
-
-
-
-
-
It’s possible to use custom types as errors by
-implementing the Error() method on them. Here’s a
-variant on the example above that uses a custom type
-to explicitly represent an argument error.
In this case we use &argError syntax to build
-a new struct, supplying values for the two
-fields arg and prob.
-
-
-
-
-
return-1,&argError{arg,"can't work with it"}
- }
- returnarg+3,nil
-}
-
-
-
-
-
-
-
-
-
-
-
-
funcmain(){
-
-
-
-
-
-
-
-
The two loops below test out each of our
-error-returning functions. Note that the use of an
-inline error check on the if line is a common
-idiom in Go code.
If you want to programmatically use the data in
-a custom error, you’ll need to get the error as an
-instance of the custom error type via type
-assertion.
@@ -299,7 +34,7 @@ on the Go blog for more on error handling.
diff --git a/public/execing-processes b/public/execing-processes
index 98ce62a..e0cc10d 100644
--- a/public/execing-processes
+++ b/public/execing-processes
@@ -2,7 +2,7 @@
- Go by Example: Exec'ing Processes
+ Go в примерах: Исполняющие процессы (Exec'ing Processes)
In the previous example we looked at
-spawning external processes. We
-do this when we need an external process accessible to
-a running Go process. Sometimes we just want to
-completely replace the current Go process with another
-(perhaps non-Go) one. To do this we’ll use Go’s
-implementation of the classic
-exec
-function.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
packagemain
-
-
-
-
-
-
-
-
-
-
-
-
import(
- "os"
- "os/exec"
- "syscall"
-)
-
-
-
-
-
-
-
-
-
-
-
-
funcmain(){
-
-
-
-
-
-
-
-
For our example we’ll exec ls. Go requires an
-absolute path to the binary we want to execute, so
-we’ll use exec.LookPath to find it (probably
-/bin/ls).
Exec requires arguments in slice form (as
-apposed to one big string). We’ll give ls a few
-common arguments. Note that the first argument should
-be the program name.
-
-
-
-
-
args:=[]string{"ls","-a","-l","-h"}
-
-
-
-
-
-
-
-
Exec also needs a set of environment variables
-to use. Here we just provide our current
-environment.
-
-
-
-
-
env:=os.Environ()
-
-
-
-
-
-
-
-
Here’s the actual syscall.Exec call. If this call is
-successful, the execution of our process will end
-here and be replaced by the /bin/ls -a -l -h
-process. If there is an error we’ll get a return
-value.
$ go run execing-processes.go
-total 16
-drwxr-xr-x 4 mark 136B Oct 3 16:29 .
-drwxr-xr-x 91 mark 3.0K Oct 3 12:50 ..
--rw-r--r-- 1 mark 1.3K Oct 3 16:28 execing-processes.go
-
-
-
-
-
-
-
-
Note that Go does not offer a classic Unix fork
-function. Usually this isn’t an issue though, since
-starting goroutines, spawning processes, and exec’ing
-processes covers most use cases for fork.
-
-
-
-
-
-
-
-
-
+
Go в примерах: Исполняющие процессы (Exec'ing Processes)
@@ -203,7 +34,7 @@ processes covers most use cases for fork.
diff --git a/public/exit b/public/exit
index 5929eb6..50c7fbe 100644
--- a/public/exit
+++ b/public/exit
@@ -2,7 +2,7 @@
- Go by Example: Exit
+ Go в примерах: Выход (Exit)
Use os.Exit to immediately exit with a given
-status.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
packagemain
-
-
-
-
-
-
-
-
-
-
-
-
import(
- "fmt"
- "os"
-)
-
-
-
-
-
-
-
-
-
-
-
-
funcmain(){
-
-
-
-
-
-
-
-
defers will not be run when using os.Exit, so
-this fmt.Println will never be called.
-
-
-
-
-
deferfmt.Println("!")
-
-
-
-
-
-
-
-
Exit with status 3.
-
-
-
-
-
os.Exit(3)
-}
-
-
-
-
-
-
-
-
Note that unlike e.g. C, Go does not use an integer
-return value from main to indicate exit status. If
-you’d like to exit with a non-zero status you should
-use os.Exit.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
If you run exit.go using go run, the exit
-will be picked up by go and printed.
-
-
-
-
-
$ go run exit.go
-exit status 3
-
-
-
-
-
-
-
-
By building and executing a binary you can see
-the status in the terminal.
-
-
-
-
-
$ go build exit.go
-$ ./exit
-$echo$?
-3
-
-
-
-
-
-
-
-
Note that the ! from our program never got printed.
diff --git a/public/file-paths b/public/file-paths
index 2351954..b026eb7 100644
--- a/public/file-paths
+++ b/public/file-paths
@@ -2,7 +2,7 @@
- Go by Example: File Paths
+ Go в примерах: Пути к файлам (File Paths)
The filepath package provides functions to parse
-and construct file paths in a way that is portable
-between operating systems; dir/file on Linux vs.
-dir\file on Windows, for example.
You should always use Join instead of
-concatenating /s or \s manually. In addition
-to providing portability, Join will also
-normalize paths by removing superfluous separators
-and directory changes.
diff --git a/public/for b/public/for
index 81b98d9..de2ea5f 100644
--- a/public/for
+++ b/public/for
@@ -2,7 +2,7 @@
- Go by Example: For
+ Go в примерах: Цикл For
diff --git a/public/functions b/public/functions
index 8880847..ef4f0db 100644
--- a/public/functions
+++ b/public/functions
@@ -2,7 +2,7 @@
- Go by Example: Functions
+ Go в примерах: Функции (Functions)
Functions are central in Go. We’ll learn about
-functions with a few different examples.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
packagemain
-
-
-
-
-
-
-
-
-
-
-
-
import"fmt"
-
-
-
-
-
-
-
-
Here’s a function that takes two ints and returns
-their sum as an int.
-
-
-
-
-
funcplus(aint,bint)int{
-
-
-
-
-
-
-
-
Go requires explicit returns, i.e. it won’t
-automatically return the value of the last
-expression.
-
-
-
-
-
returna+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.
-
-
-
-
-
funcplusPlus(a,b,cint)int{
- returna+b+c
-}
-
-
-
-
-
-
-
-
-
-
-
-
funcmain(){
-
-
-
-
-
-
-
-
Call a function just as you’d expect, with
-name(args).
When we run this program, we see the output of the
-blocking call first, then the interleaved output of the
-two goroutines. This interleaving reflects the
-goroutines being run concurrently by the Go runtime.
@@ -207,7 +34,7 @@ concurrent Go programs: channels.
diff --git a/public/hello-world b/public/hello-world
index 4c2373a..67c1c82 100644
--- a/public/hello-world
+++ b/public/hello-world
@@ -2,7 +2,7 @@
- Go by Example: Hello World
+ Go в примерах: Hello World
The Go standard library comes with excellent support
-for HTTP clients and servers in the net/http
-package. In this example we’ll use it to issue simple
-HTTP requests.
-
-
-
-
-
packagemain
-
-
-
-
-
-
-
-
-
-
-
-
import(
- "bufio"
- "fmt"
- "net/http"
-)
-
-
-
-
-
-
-
-
-
-
-
-
funcmain(){
-
-
-
-
-
-
-
-
Issue an HTTP GET request to a server. http.Get is a
-convenient shortcut around creating an http.Client
-object and calling its Get method; it uses the
-http.DefaultClient object which has useful default
-settings.
Writing a basic HTTP server is easy using the
-net/http package.
-
-
-
-
-
packagemain
-
-
-
-
-
-
-
-
-
-
-
-
import(
- "fmt"
- "net/http"
-)
-
-
-
-
-
-
-
-
A fundamental concept in net/http servers is
-handlers. A handler is an object implementing the
-http.Handler interface. A common way to write
-a handler is by using the http.HandlerFunc adapter
-on functions with the appropriate signature.
Functions serving as handlers take a
-http.ResponseWriter and a http.Request as
-arguments. The response writer is used to fill in the
-HTTP response. Here our simple response is just
-“hello\n”.
We register our handlers on server routes using the
-http.HandleFunc convenience function. It sets up
-the default router in the net/http package and
-takes a function as an argument.
- Go is an
- open source programming language designed for
- building simple, fast, and reliable software.
+ Go - это язык программирования с
+ открытым исходным кодом, предназначенный для создания простого,
+ быстрого и надежного программного обеспечения.
- Go by Example is a hands-on introduction
- to Go using annotated example programs. Check out
- the first example or
- browse the full list below.
+ Go в примерах Go by Example - это практическое введение
+ в Go с использованием примеров реальных программ. Проверьте
+ первый пример или просмотрите полный
+ список ниже.
If a variable has an interface type, then we can call
-methods that are in the named interface. Here’s a
-generic measure function taking advantage of this
-to work on any geometry.
@@ -236,7 +34,7 @@ these structs as arguments to measure.
diff --git a/public/json b/public/json
index e2327ec..9e541cf 100644
--- a/public/json
+++ b/public/json
@@ -2,7 +2,7 @@
- Go by Example: JSON
+ Go в примерах: JSON
Go offers built-in support for JSON encoding and
-decoding, including to and from built-in and custom
-data types.
+
Go предлагает встроенную поддержку кодирования и
+декодирования JSON, в том числе встроенных и
+пользовательских типов данных.
@@ -43,7 +43,7 @@ data types.
-
+
packagemain
@@ -68,8 +68,8 @@ data types.
-
We’ll use these two structs to demonstrate encoding and
-decoding of custom types below.
+
Мы будем использовать эти две структуры, для демонстрации
+кодирования и декодирования.
@@ -85,8 +85,9 @@ decoding of custom types below.
-
Only exported fields will be encoded/decoded in JSON.
-Fields must start with capital letters to be exported.
+
Только экспортируемые поля могут быть кодированы и
+декодированы в JSON. Поля должны начинаться с
+заглавной буквы.
@@ -114,9 +115,9 @@ Fields must start with capital letters to be exported.
-
First we’ll look at encoding basic data types to
-JSON strings. Here are some examples for atomic
-values.
+
Для начала мы рассмотрим кодирование данных в
+JSON строку. Вот несколько примеров для простых
+типов данных.
@@ -169,8 +170,8 @@ values.
-
And here are some for slices and maps, which encode
-to JSON arrays and objects as you’d expect.
+
А вот примеры для срезов и карт, которые кодируются
+в JSON массивы и объекты, как мы и ожидаем.
@@ -199,10 +200,11 @@ to JSON arrays and objects as you’d expect.
-
The JSON package can automatically encode your
-custom data types. It will only include exported
-fields in the encoded output and will by default
-use those names as the JSON keys.
+
Пакет JSON может автоматически кодировать ваши
+пользовательские типы данных. Он будет включать
+только экспортируемые поля в закодированный
+вывод и по умолчанию будет использовать эти
+имена в качестве ключей JSON.
@@ -219,10 +221,10 @@ use those names as the JSON keys.
-
You can use tags on struct field declarations
-to customize the encoded JSON key names. Check the
-definition of response2 above to see an example
-of such tags.
+
Вы можете использовать теги в объявлениях
+структурных полей для настройки кодированных имен
+ключей JSON. Проверьте определение response2
+выше, чтобы увидеть пример таких тегов.
@@ -239,9 +241,9 @@ of such tags.
-
Now let’s look at decoding JSON data into Go
-values. Here’s an example for a generic data
-structure.
+
Теперь давайте рассмотрим декодирование данных
+JSON в значения Go. Вот пример для общей
+структуры данных.
@@ -254,10 +256,10 @@ structure.
-
We need to provide a variable where the JSON
-package can put the decoded data. This
-map[string]interface{} will hold a map of strings
-to arbitrary data types.
+
Нам нужно предоставить переменную, в которую пакет
+JSON может поместить декодированные данные.
+`map[string]interface{} будет содержать карту
+строк для произвольных типов данных.
@@ -270,8 +272,8 @@ to arbitrary data types.
-
Here’s the actual decoding, and a check for
-associated errors.
+
Вот фактическое декодирование и проверка на наличие
+ошибок.
@@ -287,10 +289,10 @@ associated errors.
-
In order to use the values in the decoded map,
-we’ll need to convert them to their appropriate type.
-For example here we convert the value in num to
-the expected float64 type.
+
Чтобы использовать значения в декодированной карте,
+нам нужно преобразовать их в соответствующий тип.
+Например, здесь мы конвертируем значение из num
+в ожидаемый тип float64.
@@ -304,8 +306,7 @@ the expected float64 type.
-
Accessing nested data requires a series of
-conversions.
+
Доступ к вложенным данным требует ряда преобразований.
@@ -320,11 +321,11 @@ conversions.
-
We can also decode JSON into custom data types.
-This has the advantages of adding additional
-type-safety to our programs and eliminating the
-need for type assertions when accessing the decoded
-data.
+
Мы также можем декодировать JSON в пользовательские
+типы данных. Это дает преимущество добавления
+дополнительной безопасности типов в наши программы
+и устранения необходимости в определении типрв
+при доступе к декодированным данным.
@@ -341,11 +342,12 @@ data.
-
In the examples above we always used bytes and
-strings as intermediates between the data and
-JSON representation on standard out. We can also
-stream JSON encodings directly to os.Writers like
-os.Stdout or even HTTP response bodies.
+
В приведенных выше примерах мы всегда использовали
+байты и строки в качестве промежуточных звеньев между
+данными и представлением JSON на стандартном выходе.
+Мы также можем транслировать JSON-кодировки напрямую
+в os.Writer, такие как os.Stdout или даже HTTP-тела
+ответа.
@@ -391,10 +393,9 @@ stream JSON encodings directly to os.Writers like
-
We’ve covered the basic of JSON in Go here, but check
-out the JSON and Go
-blog post and JSON package docs
-for more.
+
Мы рассмотрели основы JSON в Go, но ознакомьтесь с
+публикацией в блоге JSON and Go
+и документацией по пакету JSON.
A line filter is a common type of program that reads
-input on stdin, processes it, and then prints some
-derived result to stdout. grep and sed are common
-line filters.
-
-
-
-
-
-
-
-
-
-
-
Here’s an example line filter in Go that writes a
-capitalized version of all input text. You can use this
-pattern to write your own Go line filters.
-
-
-
-
-
packagemain
-
-
-
-
-
-
-
-
-
-
-
-
import(
- "bufio"
- "fmt"
- "os"
- "strings"
-)
-
-
-
-
-
-
-
-
-
-
-
-
funcmain(){
-
-
-
-
-
-
-
-
Wrapping the unbuffered os.Stdin with a buffered
-scanner gives us a convenient Scan method that
-advances the scanner to the next token; which is
-the next line in the default scanner.
-
-
-
-
-
scanner:=bufio.NewScanner(os.Stdin)
-
-
-
-
-
-
-
-
Text returns the current token, here the next line,
-from the input.
-
-
-
-
-
forscanner.Scan(){
-
-
-
-
-
-
-
-
-
-
-
-
ucl:=strings.ToUpper(scanner.Text())
-
-
-
-
-
-
-
-
Write out the uppercased line.
-
-
-
-
-
fmt.Println(ucl)
- }
-
-
-
-
-
-
-
-
Check for errors during Scan. End of file is
-expected and not reported by Scan as an error.
diff --git a/public/maps b/public/maps
index 443efd7..8d69719 100644
--- a/public/maps
+++ b/public/maps
@@ -2,7 +2,7 @@
- Go by Example: Maps
+ Go в примерах: Карты (Maps)
Maps are Go’s built-in associative data type
-(sometimes called hashes or dicts in other languages).
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
packagemain
-
-
-
-
-
-
-
-
-
-
-
-
import"fmt"
-
-
-
-
-
-
-
-
-
-
-
-
funcmain(){
-
-
-
-
-
-
-
-
To create an empty map, use the builtin make:
-make(map[key-type]val-type).
-
-
-
-
-
m:=make(map[string]int)
-
-
-
-
-
-
-
-
Set key/value pairs using typical name[key] = val
-syntax.
-
-
-
-
-
m["k1"]=7
- m["k2"]=13
-
-
-
-
-
-
-
-
Printing a map with e.g. fmt.Println will show all of
-its key/value pairs.
-
-
-
-
-
fmt.Println("map:",m)
-
-
-
-
-
-
-
-
Get a value for a key with name[key].
-
-
-
-
-
v1:=m["k1"]
- fmt.Println("v1: ",v1)
-
-
-
-
-
-
-
-
The builtin len returns the number of key/value
-pairs when called on a map.
-
-
-
-
-
fmt.Println("len:",len(m))
-
-
-
-
-
-
-
-
The builtin delete removes key/value pairs from
-a map.
-
-
-
-
-
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
-_.
-
-
-
-
-
_,prs:=m["k2"]
- fmt.Println("prs:",prs)
-
-
-
-
-
-
-
-
You can also declare and initialize a new map in
-the same line with this syntax.
diff --git a/public/methods b/public/methods
index ca0589a..268a326 100644
--- a/public/methods
+++ b/public/methods
@@ -2,7 +2,7 @@
- Go by Example: Methods
+ Go в примерах: Методы (Methods)
Go automatically handles conversion between values
-and pointers for method calls. You may want to use
-a pointer receiver type to avoid copying on method
-calls or to allow the method to mutate the
-receiving struct.
@@ -197,7 +34,7 @@ naming related sets of methods: interfaces.
diff --git a/public/multiple-return-values b/public/multiple-return-values
index bd16bd1..fc6717b 100644
--- a/public/multiple-return-values
+++ b/public/multiple-return-values
@@ -2,7 +2,7 @@
- Go by Example: Multiple Return Values
+ Go в примерах: Функции с множественным возвратом (Multiple Return Values)
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.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
packagemain
-
-
-
-
-
-
-
-
-
-
-
-
import"fmt"
-
-
-
-
-
-
-
-
The (int, int) in this function signature shows that
-the function returns 2 ints.
-
-
-
-
-
funcvals()(int,int){
- return3,7
-}
-
-
-
-
-
-
-
-
-
-
-
-
funcmain(){
-
-
-
-
-
-
-
-
Here we use the 2 different return values from the
-call with multiple assignment.
-
-
-
-
-
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)
-}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
$ go run multiple-return-values.go
-3
-7
-7
-
-
-
-
-
-
-
-
Accepting a variable number of arguments is another nice
-feature of Go functions; we’ll look at this next.
-
-
-
-
-
-
-
-
-
+
Go в примерах: Функции с множественным возвратом (Multiple Return Values)
In the previous example we saw how to manage simple
-counter state using atomic operations.
-For more complex state we can use a mutex
-to safely access data across multiple goroutines.
For each read we pick a key to access,
-Lock() the mutex to ensure
-exclusive access to the state, read
-the value at the chosen key,
-Unlock() the mutex, and increment
-the readOps count.
@@ -297,7 +34,7 @@ management task using only goroutines and channels.
diff --git a/public/non-blocking-channel-operations b/public/non-blocking-channel-operations
index bbe6d55..754f365 100644
--- a/public/non-blocking-channel-operations
+++ b/public/non-blocking-channel-operations
@@ -2,7 +2,7 @@
- Go by Example: Non-Blocking Channel Operations
+ Go в примерах: Неблокируемые операции в каналах (Non-Blocking Channel Operations)
Basic sends and receives on channels are blocking.
-However, we can use select with a default clause to
-implement non-blocking sends, receives, and even
-non-blocking multi-way selects.
Here’s a non-blocking receive. If a value is
-available on messages then select will take
-the <-messagescase with that value. If not
-it will immediately take the default case.
A non-blocking send works similarly. Here msg
-cannot be sent to the messages channel, because
-the channel has no buffer and there is no receiver.
-Therefore the default case is selected.
We can use multiple cases above the default
-clause to implement a multi-way non-blocking
-select. Here we attempt non-blocking receives
-on both messages and signals.
diff --git a/public/number-parsing b/public/number-parsing
index 269da85..1cf3b50 100644
--- a/public/number-parsing
+++ b/public/number-parsing
@@ -2,7 +2,7 @@
- Go by Example: Number Parsing
+ Go в примерах: Парсинг чисел (Number Parsing)
diff --git a/public/panic b/public/panic
index 6a9b834..d393582 100644
--- a/public/panic
+++ b/public/panic
@@ -2,7 +2,7 @@
- Go by Example: Panic
+ Go в примерах: Panic
A panic typically means something went unexpectedly
-wrong. Mostly we use it to fail fast on errors that
-shouldn’t occur during normal operation, or that we
-aren’t prepared to handle gracefully.
+
Panic обычно означает, что что-то неожиданно пошло
+не так. В основном мы используем его для быстрого
+отказа при ошибках, которые не должны возникать во
+время нормальной работы, или которые мы не готовы
+обрабатывать.
@@ -44,7 +45,7 @@ aren’t prepared to handle gracefully.
-
+
packagemain
@@ -77,9 +78,10 @@ aren’t prepared to handle gracefully.
-
We’ll use panic throughout this site to check for
-unexpected errors. This is the only program on the
-site designed to panic.
+
Мы будем использовать panic на этом сайте, чтобы
+проверять наличие неожиданных ошибок. Это
+единственная программа на сайте, предназначенная
+для паники.
@@ -92,10 +94,11 @@ site designed to panic.
-
A common use of panic is to abort if a function
-returns an error value that we don’t know how to
-(or want to) handle. Here’s an example of
-panicking if we get an unexpected error when creating a new file.
+
Обычное использование panic - это прерывание,
+если функция возвращает значение ошибки, которое
+мы не знаем, как (или хотим) обрабатывать. Вот
+пример panic, если мы получаем неожиданную ошибку
+при создании нового файла.
@@ -116,9 +119,9 @@ returns an error value that we don’t know how to
-
Running this program will cause it to panic, print
-an error message and goroutine traces, and exit with
-a non-zero status.
+
Запуск этой программы вызовет панику, распечатает
+сообщение об ошибке и трейс выполнения и завершит
+работу с ненулевым статусом.
@@ -148,9 +151,10 @@ a non-zero status.
-
Note that unlike some languages which use exceptions
-for handling of many errors, in Go it is idiomatic
-to use error-indicating return values wherever possible.
+
Обратите внимание, что в отличие от некоторых языков,
+которые используют исключения для обработки
+ошибок, в Go привычно использовать возвращающие
+значения, указывающие на ошибки.
@@ -163,7 +167,7 @@ to use error-indicating return values wherever possible.
Go supports pointers,
-allowing you to pass references to values and records
-within your program.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
packagemain
-
-
-
-
-
-
-
-
-
-
-
-
import"fmt"
-
-
-
-
-
-
-
-
We’ll show how pointers work in contrast to values with
-2 functions: zeroval and zeroptr. zeroval has an
-int parameter, so arguments will be passed to it by
-value. zeroval will get a copy of ival distinct
-from the one in the calling function.
-
-
-
-
-
funczeroval(ivalint){
- ival=0
-}
-
-
-
-
-
-
-
-
zeroptr in contrast has an *int parameter, meaning
-that it takes an int pointer. The *iptr code in the
-function body then dereferences the pointer from its
-memory address to the current value at that address.
-Assigning a value to a dereferenced pointer changes the
-value at the referenced address.
-
-
-
-
-
funczeroptr(iptr*int){
- *iptr=0
-}
-
-
-
-
-
-
-
-
-
-
-
-
funcmain(){
- i:=1
- fmt.Println("initial:",i)
-
-
-
-
-
-
-
-
-
-
-
-
zeroval(i)
- fmt.Println("zeroval:",i)
-
-
-
-
-
-
-
-
The &i syntax gives the memory address of i,
-i.e. a pointer to i.
-
-
-
-
-
zeroptr(&i)
- fmt.Println("zeroptr:",i)
-
-
-
-
-
-
-
-
Pointers can be printed too.
-
-
-
-
-
fmt.Println("pointer:",&i)
-}
-
-
-
-
-
-
-
-
-
-
-
-
zeroval doesn’t change the i in main, but
-zeroptr does because it has a reference to
-the memory address for that variable.
-
-
-
-
-
$ go run pointers.go
-initial: 1
-zeroval: 1
-zeroptr: 0
-pointer: 0x42131100
-
@@ -193,7 +34,7 @@ the memory address for that variable.
diff --git a/public/random-numbers b/public/random-numbers
index d3685c5..eb1856a 100644
--- a/public/random-numbers
+++ b/public/random-numbers
@@ -2,7 +2,7 @@
- Go by Example: Random Numbers
+ Go в примерах: Случайные числа (Random Numbers)
The default number generator is deterministic, so it’ll
-produce the same sequence of numbers each time by default.
-To produce varying sequences, give it a seed that changes.
-Note that this is not safe to use for random numbers you
-intend to be secret, use crypto/rand for those.
diff --git a/public/range b/public/range
index f09b0c7..17e52bb 100644
--- a/public/range
+++ b/public/range
@@ -2,7 +2,7 @@
- Go by Example: Range
+ Go в примерах: Ряд (Range)
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.
@@ -200,7 +34,7 @@ of the rune and the second the rune itself.
diff --git a/public/range-over-channels b/public/range-over-channels
index 1b7354c..e9724c5 100644
--- a/public/range-over-channels
+++ b/public/range-over-channels
@@ -2,7 +2,7 @@
- Go by Example: Range over Channels
+ Go в примерах: Перебор значений из каналов (Range over Channels)
In a previous example we saw how for and
-range provide iteration over basic data structures.
-We can also use this syntax to iterate over
-values received from a channel.
This range iterates over each element as it’s
-received from queue. Because we closed the
-channel above, the iteration terminates after
-receiving the 2 elements.
-
-
-
-
-
forelem:=rangequeue{
- fmt.Println(elem)
- }
-}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
$ go run range-over-channels.go
-one
-two
-
-
-
-
-
-
-
-
This example also showed that it’s possible to close
-a non-empty channel but still have the remaining
-values be received.
-
-
-
-
-
-
-
-
-
+
Go в примерах: Перебор значений из каналов (Range over Channels)
diff --git a/public/rate-limiting b/public/rate-limiting
index 33dd251..e55807e 100644
--- a/public/rate-limiting
+++ b/public/rate-limiting
@@ -2,7 +2,7 @@
- Go by Example: Rate Limiting
+ Go в примерах: Ограничение скорости (Rate Limiting)
Rate limiting
-is an important mechanism for controlling resource
-utilization and maintaining quality of service. Go
-elegantly supports rate limiting with goroutines,
-channels, and tickers.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
packagemain
-
-
-
-
-
-
-
-
-
-
-
-
import(
- "fmt"
- "time"
-)
-
-
-
-
-
-
-
-
-
-
-
-
funcmain(){
-
-
-
-
-
-
-
-
First we’ll look at basic rate limiting. Suppose
-we want to limit our handling of incoming requests.
-We’ll serve these requests off a channel of the
-same name.
We may want to allow short bursts of requests in
-our rate limiting scheme while preserving the
-overall rate limit. We can accomplish this by
-buffering our limiter channel. This burstyLimiter
-channel will allow bursts of up to 3 events.
-
-
-
-
-
burstyLimiter:=make(chantime.Time,3)
-
-
-
-
-
-
-
-
Fill up the channel to represent allowed bursting.
Running our program we see the first batch of requests
-handled once every ~200 milliseconds as desired.
-
-
-
-
-
$ go run rate-limiting.go
-request 1 2012-10-19 00:38:18.687438 +0000 UTC
-request 2 2012-10-19 00:38:18.887471 +0000 UTC
-request 3 2012-10-19 00:38:19.087238 +0000 UTC
-request 4 2012-10-19 00:38:19.287338 +0000 UTC
-request 5 2012-10-19 00:38:19.487331 +0000 UTC
-
-
-
-
-
-
-
-
For the second batch of requests we serve the first
-3 immediately because of the burstable rate limiting,
-then serve the remaining 2 with ~200ms delays each.
-
-
-
-
-
request 1 2012-10-19 00:38:20.487578 +0000 UTC
-request 2 2012-10-19 00:38:20.487645 +0000 UTC
-request 3 2012-10-19 00:38:20.487676 +0000 UTC
-request 4 2012-10-19 00:38:20.687483 +0000 UTC
-request 5 2012-10-19 00:38:20.887542 +0000 UTC
-
The io package provides some functions that may
-be helpful for file reading. For example, reads
-like the ones above can be more robustly
-implemented with ReadAtLeast.
There is no built-in rewind, but Seek(0, 0)
-accomplishes this.
-
-
-
-
-
_,err=f.Seek(0,0)
- check(err)
-
-
-
-
-
-
-
-
The bufio package implements a buffered
-reader that may be useful both for its efficiency
-with many small reads and because of the additional
-reading methods it provides.
Above we used a string pattern directly, but for
-other regexp tasks you’ll need to Compile an
-optimized Regexp struct.
-
-
-
-
-
r,_:=regexp.Compile("p([a-z]+)ch")
-
-
-
-
-
-
-
-
Many methods are available on these structs. Here’s
-a match test like we saw earlier.
-
-
-
-
-
fmt.Println(r.MatchString("peach"))
-
-
-
-
-
-
-
-
This finds the match for the regexp.
-
-
-
-
-
fmt.Println(r.FindString("peach punch"))
-
-
-
-
-
-
-
-
This also finds the first match but returns the
-start and end indexes for the match instead of the
-matching text.
-
-
-
-
-
fmt.Println(r.FindStringIndex("peach punch"))
-
-
-
-
-
-
-
-
The Submatch variants include information about
-both the whole-pattern matches and the submatches
-within those matches. For example this will return
-information for both p([a-z]+)ch and ([a-z]+).
Our examples above had string arguments and used
-names like MatchString. We can also provide
-[]byte arguments and drop String from the
-function name.
-
-
-
-
-
fmt.Println(r.Match([]byte("peach")))
-
-
-
-
-
-
-
-
When creating constants with regular expressions
-you can use the MustCompile variation of
-Compile. A plain Compile won’t work for
-constants because it has 2 return values.
diff --git a/public/select b/public/select
index 116ac3b..f45e57e 100644
--- a/public/select
+++ b/public/select
@@ -2,7 +2,7 @@
- Go by Example: Select
+ Go в примерах: Select
SHA1 hashes are
-frequently used to compute short identities for binary
-or text blobs. For example, the git revision control
-system uses SHA1s extensively to
-identify versioned files and directories. Here’s how to
-compute SHA1 hashes in Go.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
packagemain
-
-
-
-
-
-
-
-
Go implements several hash functions in various
-crypto/* packages.
-
-
-
-
-
import(
- "crypto/sha1"
- "fmt"
-)
-
-
-
-
-
-
-
-
-
-
-
-
funcmain(){
- s:="sha1 this string"
-
-
-
-
-
-
-
-
The pattern for generating a hash is sha1.New(),
-sha1.Write(bytes), then sha1.Sum([]byte{}).
-Here we start with a new hash.
-
-
-
-
-
h:=sha1.New()
-
-
-
-
-
-
-
-
Write expects bytes. If you have a string s,
-use []byte(s) to coerce it to bytes.
-
-
-
-
-
h.Write([]byte(s))
-
-
-
-
-
-
-
-
This gets the finalized hash result as a byte
-slice. The argument to Sum can be used to append
-to an existing byte slice: it usually isn’t needed.
-
-
-
-
-
bs:=h.Sum(nil)
-
-
-
-
-
-
-
-
SHA1 values are often printed in hex, for example
-in git commits. Use the %x format verb to convert
-a hash results to a hex string.
-
-
-
-
-
fmt.Println(s)
- fmt.Printf("%x\n",bs)
-}
-
-
-
-
-
-
-
-
-
-
-
-
Running the program computes the hash and prints it in
-a human-readable hex format.
-
-
-
-
-
$ go run sha1-hashes.go
-sha1 this string
-cf23df2207d99a74fbe169e3eba035e633b65d94
-
-
-
-
-
-
-
-
You can compute other hashes using a similar pattern to
-the one shown above. For example, to compute MD5 hashes
-import crypto/md5 and use md5.New().
-
-
-
-
-
-
-
-
-
-
-
Note that if you need cryptographically secure hashes,
-you should carefully research
-hash strength!
Sometimes we’d like our Go programs to intelligently
-handle Unix signals.
-For example, we might want a server to gracefully
-shutdown when it receives a SIGTERM, or a command-line
-tool to stop processing input if it receives a SIGINT.
-Here’s how to handle signals in Go with channels.
Go signal notification works by sending os.Signal
-values on a channel. We’ll create a channel to
-receive these notifications (we’ll also make one to
-notify us when the program can exit).
When we run this program it will block waiting for a
-signal. By typing ctrl-C (which the
-terminal shows as ^C) we can send a SIGINT signal,
-causing the program to print interrupt and then exit.
-
-
-
-
-
$ go run signals.go
-awaiting signal
-^C
-interrupt
-exiting
-
Slices are a key data type in Go, giving a more
-powerful interface to sequences than arrays.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
packagemain
-
-
-
-
-
-
-
-
-
-
-
-
import"fmt"
-
-
-
-
-
-
-
-
-
-
-
-
funcmain(){
-
-
-
-
-
-
-
-
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
-strings of length 3 (initially zero-valued).
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.
Note that while slices are different types than arrays,
-they are rendered similarly by fmt.Println.
-
-
-
-
-
$ go run slices.go
-emp: [ ]
-set: [a b c]
-get: c
-len: 3
-apd: [a b c d e f]
-cpy: [a b c d e f]
-sl1: [c d e]
-sl2: [a b c d e]
-sl3: [c d e f]
-dcl: [g h i]
-2d: [[0] [1 2] [2 3 4]]
-
-
-
-
-
-
-
-
Check out this great blog post
-by the Go team for more details on the design and
-implementation of slices in Go.
-
-
-
-
-
-
-
-
-
-
-
Now that we’ve seen arrays and slices we’ll look at
-Go’s other key builtin data structure: maps.
Go’s sort package implements sorting for builtins
-and user-defined types. We’ll look at sorting for
-builtins first.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
packagemain
-
-
-
-
-
-
-
-
-
-
-
-
import(
- "fmt"
- "sort"
-)
-
-
-
-
-
-
-
-
-
-
-
-
funcmain(){
-
-
-
-
-
-
-
-
Sort methods are specific to the builtin type;
-here’s an example for strings. Note that sorting is
-in-place, so it changes the given slice and doesn’t
-return a new one.
@@ -160,7 +34,7 @@ slices and true as the result of our AreSorted test.
diff --git a/public/sorting-by-functions b/public/sorting-by-functions
index f86a188..fb1f2fa 100644
--- a/public/sorting-by-functions
+++ b/public/sorting-by-functions
@@ -2,7 +2,7 @@
- Go by Example: Sorting by Functions
+ Go в примерах: Сортировка через функции (Sorting by Functions)
Sometimes we’ll want to sort a collection by something
-other than its natural order. For example, suppose we
-wanted to sort strings by their length instead of
-alphabetically. Here’s an example of custom sorts
-in Go.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
packagemain
-
-
-
-
-
-
-
-
-
-
-
-
import(
- "fmt"
- "sort"
-)
-
-
-
-
-
-
-
-
In order to sort by a custom function in Go, we need a
-corresponding type. Here we’ve created a byLength
-type that is just an alias for the builtin []string
-type.
-
-
-
-
-
typebyLength[]string
-
-
-
-
-
-
-
-
We implement sort.Interface - Len, Less, and
-Swap - on our type so we can use the sort package’s
-generic Sort function. Len and Swap
-will usually be similar across types and Less will
-hold the actual custom sorting logic. In our case we
-want to sort in order of increasing string length, so
-we use len(s[i]) and len(s[j]) here.
With all of this in place, we can now implement our
-custom sort by converting the original fruits slice
-to byLength, and then use sort.Sort on that typed
-slice.
Running our program shows a list sorted by string
-length, as desired.
-
-
-
-
-
$ go run sorting-by-functions.go
-[kiwi peach banana]
-
-
-
-
-
-
-
-
By following this same pattern of creating a custom
-type, implementing the three Interface methods on that
-type, and then calling sort.Sort on a collection of that
-custom type, we can sort Go slices by arbitrary
-functions.
-
-
-
-
-
-
-
-
-
+
Go в примерах: Сортировка через функции (Sorting by Functions)
diff --git a/public/spawning-processes b/public/spawning-processes
index da8dfc5..1cc1f34 100644
--- a/public/spawning-processes
+++ b/public/spawning-processes
@@ -2,14 +2,14 @@
- Go by Example: Spawning Processes
+ Go в примерах: Порождающие процессы (Spawning Processes)
Sometimes our Go programs need to spawn other, non-Go
-processes. For example, the syntax highlighting on this
-site is implemented
-by spawning a pygmentize
-process from a Go program. Let’s look at a few examples
-of spawning processes from Go.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
packagemain
-
-
-
-
-
-
-
-
-
-
-
-
import(
- "fmt"
- "io/ioutil"
- "os/exec"
-)
-
-
-
-
-
-
-
-
-
-
-
-
funcmain(){
-
-
-
-
-
-
-
-
We’ll start with a simple command that takes no
-arguments or input and just prints something to
-stdout. The exec.Command helper creates an object
-to represent this external process.
-
-
-
-
-
dateCmd:=exec.Command("date")
-
-
-
-
-
-
-
-
.Output is another helper that handles the common
-case of running a command, waiting for it to finish,
-and collecting its output. If there were no errors,
-dateOut will hold bytes with the date info.
Next we’ll look at a slightly more involved case
-where we pipe data to the external process on its
-stdin and collect the results from its stdout.
-
-
-
-
-
grepCmd:=exec.Command("grep","hello")
-
-
-
-
-
-
-
-
Here we explicitly grab input/output pipes, start
-the process, write some input to it, read the
-resulting output, and finally wait for the process
-to exit.
We ommited error checks in the above example, but
-you could use the usual if err != nil pattern for
-all of them. We also only collect the StdoutPipe
-results, but you could collect the StderrPipe in
-exactly the same way.
Note that when spawning commands we need to
-provide an explicitly delineated command and
-argument array, vs. being able to just pass in one
-command-line string. If you want to spawn a full
-command with a string, you can use bash’s -c
-option:
-
-
-
-
-
lsCmd:=exec.Command("bash","-c","ls -a -l -h")
- lsOut,err:=lsCmd.Output()
- iferr!=nil{
- panic(err)
- }
- fmt.Println("> ls -a -l -h")
- fmt.Println(string(lsOut))
-}
-
-
-
-
-
-
-
-
-
-
-
-
The spawned programs return output that is the same
-as if we had run them directly from the command-line.
-
-
-
-
-
$ go run spawning-processes.go
-> date
-Wed Oct 10 09:53:11 PDT 2012
-
-
-
-
-
-
-
-
-
-
-
-
> grep hello
-hello grep
-
-
-
-
-
-
-
-
-
-
-
-
> ls -a -l -h
-drwxr-xr-x 4 mark 136B Oct 3 16:29 .
-drwxr-xr-x 91 mark 3.0K Oct 3 12:50 ..
--rw-r--r-- 1 mark 1.3K Oct 3 16:28 spawning-processes.go
-
-
-
-
-
-
+
Go в примерах: Порождающие процессы (Spawning Processes)
@@ -259,7 +34,7 @@ as if we had run them directly from the command-line.
diff --git a/public/stateful-goroutines b/public/stateful-goroutines
index 80ad0ba..df7ce5a 100644
--- a/public/stateful-goroutines
+++ b/public/stateful-goroutines
@@ -2,7 +2,7 @@
- Go by Example: Stateful Goroutines
+ Go в примерах: Управление состоянием горутин (Stateful Goroutines)
In the previous example we used explicit locking with
-mutexes to synchronize access to shared state
-across multiple goroutines. Another option is to use the
-built-in synchronization features of goroutines and
-channels to achieve the same result. This channel-based
-approach aligns with Go’s ideas of sharing memory by
-communicating and having each piece of data owned
-by exactly 1 goroutine.
In this example our state will be owned by a single
-goroutine. This will guarantee that the data is never
-corrupted with concurrent access. In order to read or
-write that state, other goroutines will send messages
-to the owning goroutine and receive corresponding
-replies. These readOp and writeOpstructs
-encapsulate those requests and a way for the owning
-goroutine to respond.
Here is the goroutine that owns the state, which
-is a map as in the previous example but now private
-to the stateful goroutine. This goroutine repeatedly
-selects on the reads and writes channels,
-responding to requests as they arrive. A response
-is executed by first performing the requested
-operation and then sending a value on the response
-channel resp to indicate success (and the desired
-value in the case of reads).
This starts 100 goroutines to issue reads to the
-state-owning goroutine via the reads channel.
-Each read requires constructing a readOp, sending
-it over the reads channel, and the receiving the
-result over the provided resp channel.
Running our program shows that the goroutine-based
-state management example completes about 80,000
-total operations.
-
-
-
-
-
$ go run stateful-goroutines.go
-readOps: 71708
-writeOps: 7177
-
-
-
-
-
-
-
-
For this particular case the goroutine-based approach
-was a bit more involved than the mutex-based one. It
-might be useful in certain cases though, for example
-where you have other channels involved or when managing
-multiple such mutexes would be error-prone. You should
-use whichever approach feels most natural, especially
-with respect to understanding the correctness of your
-program.
-
-
-
-
-
-
-
-
-
+
Go в примерах: Управление состоянием горутин (Stateful Goroutines)
As with integers seen earlier, %x renders
-the string in base-16, with two output characters
-per byte of input.
-
-
-
-
-
fmt.Printf("%x\n","hex this")
-
-
-
-
-
-
-
-
To print a representation of a pointer, use %p.
-
-
-
-
-
fmt.Printf("%p\n",&p)
-
-
-
-
-
-
-
-
When formatting numbers you will often want to
-control the width and precision of the resulting
-figure. To specify the width of an integer, use a
-number after the % in the verb. By default the
-result will be right-justified and padded with
-spaces.
-
-
-
-
-
fmt.Printf("|%6d|%6d|\n",12,345)
-
-
-
-
-
-
-
-
You can also specify the width of printed floats,
-though usually you’ll also want to restrict the
-decimal precision at the same time with the
-width.precision syntax.
-
-
-
-
-
fmt.Printf("|%6.2f|%6.2f|\n",1.2,3.45)
-
-
-
-
-
-
-
-
To left-justify, use the - flag.
-
-
-
-
-
fmt.Printf("|%-6.2f|%-6.2f|\n",1.2,3.45)
-
-
-
-
-
-
-
-
You may also want to control width when formatting
-strings, especially to ensure that they align in
-table-like output. For basic right-justified width.
-
-
-
-
-
fmt.Printf("|%6s|%6s|\n","foo","b")
-
-
-
-
-
-
-
-
To left-justify use the - flag as with numbers.
-
-
-
-
-
fmt.Printf("|%-6s|%-6s|\n","foo","b")
-
-
-
-
-
-
-
-
So far we’ve seen Printf, which prints the
-formatted string to os.Stdout. Sprintf formats
-and returns a string without printing it anywhere.
@@ -457,7 +34,7 @@ and returns a string without printing it anywhere.
diff --git a/public/string-functions b/public/string-functions
index 093c467..04ab05a 100644
--- a/public/string-functions
+++ b/public/string-functions
@@ -2,7 +2,7 @@
- Go by Example: String Functions
+ Go в примерах: Строковые функции (String Functions)
The standard library’s strings package provides many
-useful string-related functions. Here are some examples
-to give you a sense of the package.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
packagemain
-
-
-
-
-
-
-
-
-
-
-
-
import(
- "fmt"
- s"strings"
-)
-
-
-
-
-
-
-
-
We alias fmt.Println to a shorter name as we’ll use
-it a lot below.
-
-
-
-
-
varp=fmt.Println
-
-
-
-
-
-
-
-
-
-
-
-
funcmain(){
-
-
-
-
-
-
-
-
Here’s a sample of the functions available in
-strings. Since these are functions from the
-package, not methods on the string object itself,
-we need pass the string in question as the first
-argument to the function. You can find more
-functions in the strings
-package docs.
Note that len and indexing above work at the byte level.
-Go uses UTF-8 encoded strings, so this is often useful
-as-is. If you’re working with potentially multi-byte
-characters you’ll want to use encoding-aware operations.
-See strings, bytes, runes and characters in Go
-for more information.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
$ go run string-functions.go
-Contains: true
-Count: 2
-HasPrefix: true
-HasSuffix: true
-Index: 1
-Join: a-b
-Repeat: aaaaa
-Replace: f00
-Replace: f0o
-Split: [a b c d e]
-ToLower: test
-ToUpper: TEST
-
diff --git a/public/structs b/public/structs
index 672b214..fadbae1 100644
--- a/public/structs
+++ b/public/structs
@@ -2,7 +2,7 @@
- Go by Example: Structs
+ Go в примерах: Структуры (Structs)
@@ -266,7 +34,7 @@ pointers are automatically dereferenced.
diff --git a/public/switch b/public/switch
index f0eff96..4f7cf2f 100644
--- a/public/switch
+++ b/public/switch
@@ -2,7 +2,7 @@
- Go by Example: Switch
+ Go в примерах: Switch
Switch statements express conditionals across many
-branches.
+
Switch помогает проверять условие в нескольких блоках
@@ -42,7 +41,7 @@ branches.
-
+
packagemain
@@ -78,7 +77,7 @@ branches.
-
Here’s a basic switch.
+
Стандартное использование switch.
@@ -100,9 +99,10 @@ branches.
-
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.
@@ -120,9 +120,9 @@ in the same case statement. We use the optional
-
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 можно использовать не только константы.
@@ -141,10 +141,9 @@ to express if/else logic. Here we also show how the
-
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 сравниваются типы значений.
+Вы можете использовать этот прием, для определения
+типа значения интерфейса.
@@ -194,7 +193,7 @@ type corresponding to its clause.
Throughout program execution, we often want to create
-data that isn’t needed after the program exits.
-Temporary files and directories are useful for this
-purpose since they don’t pollute the file system over
-time.
The easiest way to create a temporary file is by
-calling ioutil.TempFile. It creates a file and
-opens it for reading and writing. We provide ""
-as the first argument, so ioutil.TempFile will
-create the file in the default location for our OS.
Display the name of the temporary file. On
-Unix-based OSes the directory will likely be /tmp.
-The file name starts with the prefix given as the
-second argument to ioutil.TempFile and the rest
-is chosen automatically to ensure that concurrent
-calls will always create different file names.
-
-
-
-
-
fmt.Println("Temp file name:",f.Name())
-
-
-
-
-
-
-
-
Clean up the file after we’re done. The OS is
-likely to clean up temporary files by itself after
-some time, but it’s good practice to do this
-explicitly.
-
-
-
-
-
deferos.Remove(f.Name())
-
-
-
-
-
-
-
-
We can write some data to the file.
-
-
-
-
-
_,err=f.Write([]byte{1,2,3,4})
- check(err)
-
-
-
-
-
-
-
-
If we intend to write many temporary files, we may
-prefer to create a temporary directory.
-ioutil.TempDir’s arguments are the same as
-TempFile’s, but it returns a directory name
-rather than an open file.
-
-
-
-
-
dname,err:=ioutil.TempDir("","sampledir")
- fmt.Println("Temp dir name:",dname)
-
-
-
-
-
-
-
-
-
-
-
-
deferos.RemoveAll(dname)
-
-
-
-
-
-
-
-
Now we can synthesize temporary file names by
-prefixing them with our temporary directory.
Unit testing is an important part of writing
-principled Go programs. The testing package
-provides the tools we need to write unit tests
-and the go test command runs tests.
-
-
-
-
-
-
-
-
-
-
-
For the sake of demonstration, this code is in package
-main, but it could be any package. Testing code
-typically lives in the same package as the code it tests.
-
-
-
-
-
packagemain
-
-
-
-
-
-
-
-
-
-
-
-
import(
- "fmt"
- "testing"
-)
-
-
-
-
-
-
-
-
We’ll be testing this simple implementation of an
-integer minimum. Typically, the code we’re testing
-would be in a source file named something like
-intutils.go, and the test file for it would then
-be named intutils_test.go.
Writing tests can be repetitive, so it’s idiomatic to
-use a table-driven style, where test inputs and
-expected outputs are listed in a table and a single loop
-walks over them and performs the test logic.
Timers are for when you want to do
-something once in the future - tickers are for when
-you want to do something repeatedly at regular
-intervals. Here’s an example of a ticker that ticks
-periodically until we stop it.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
packagemain
-
-
-
-
-
-
-
-
-
-
-
-
import(
- "fmt"
- "time"
-)
-
-
-
-
-
-
-
-
-
-
-
-
funcmain(){
-
-
-
-
-
-
-
-
Tickers use a similar mechanism to timers: a
-channel that is sent values. Here we’ll use the
-range builtin on the channel to iterate over
-the values as they arrive every 500ms.
When we run this program the ticker should tick 3 times
-before we stop it.
-
-
-
-
-
$ go run tickers.go
-Tick at 2012-09-23 11:29:56.487625 -0700 PDT
-Tick at 2012-09-23 11:29:56.988063 -0700 PDT
-Tick at 2012-09-23 11:29:57.488076 -0700 PDT
-Ticker stopped
-
diff --git a/public/time b/public/time
index 12137d8..75f4c6d 100644
--- a/public/time
+++ b/public/time
@@ -2,7 +2,7 @@
- Go by Example: Time
+ Go в примерах: Время (Time)
diff --git a/public/time-formatting-parsing b/public/time-formatting-parsing
index 5c8f266..176c27a 100644
--- a/public/time-formatting-parsing
+++ b/public/time-formatting-parsing
@@ -2,7 +2,7 @@
- Go by Example: Time Formatting / Parsing
+ Go в примерах: Форматирование времени (Time Formatting / Parsing)
Format and Parse use example-based layouts. Usually
-you’ll use a constant from time for these layouts, but
-you can also supply custom layouts. Layouts must use the
-reference time Mon Jan 2 15:04:05 MST 2006 to show the
-pattern with which to format/parse a given time/string.
-The example time must be exactly as shown: the year 2006,
-15 for the hour, Monday for the day of the week, etc.
Timeouts are important for programs that connect to
-external resources or that otherwise need to bound
-execution time. Implementing timeouts in Go is easy and
-elegant thanks to channels and select.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
packagemain
-
-
-
-
-
-
-
-
-
-
-
-
import(
- "fmt"
- "time"
-)
-
-
-
-
-
-
-
-
-
-
-
-
funcmain(){
-
-
-
-
-
-
-
-
For our example, suppose we’re executing an external
-call that returns its result on a channel c1
-after 2s. Note that the channel is buffered, so the
-send in the goroutine is nonblocking. This is a
-common pattern to prevent goroutine leaks in case the
-channel is never read.
Here’s the select implementing a timeout.
-res := <-c1 awaits the result and <-Time.After
-awaits a value to be sent after the timeout of
-1s. Since select proceeds with the first
-receive that’s ready, we’ll take the timeout case
-if the operation takes more than the allowed 1s.
We often want to execute Go code at some point in the
-future, or repeatedly at some interval. Go’s built-in
-timer and ticker features make both of these tasks
-easy. We’ll look first at timers and then
-at tickers.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
packagemain
-
-
-
-
-
-
-
-
-
-
-
-
import(
- "fmt"
- "time"
-)
-
-
-
-
-
-
-
-
-
-
-
-
funcmain(){
-
-
-
-
-
-
-
-
Timers represent a single event in the future. You
-tell the timer how long you want to wait, and it
-provides a channel that will be notified at that
-time. This timer will wait 2 seconds.
-
-
-
-
-
timer1:=time.NewTimer(2*time.Second)
-
-
-
-
-
-
-
-
The <-timer1.C blocks on the timer’s channel C
-until it sends a value indicating that the timer
-expired.
-
-
-
-
-
<-timer1.C
- fmt.Println("Timer 1 expired")
-
-
-
-
-
-
-
-
If you just wanted to wait, you could have used
-time.Sleep. One reason a timer may be useful is
-that you can cancel the timer before it expires.
-Here’s an example of that.
Here we extract the path and the fragment after
-the #.
-
-
-
-
-
fmt.Println(u.Path)
- fmt.Println(u.Fragment)
-
-
-
-
-
-
-
-
To get query params in a string of k=v format,
-use RawQuery. You can also parse query params
-into a map. The parsed query param maps are from
-strings to slices of strings, so index into [0]
-if you only want the first value.
@@ -183,7 +34,7 @@ initializing a variable, e.g. for
diff --git a/public/variadic-functions b/public/variadic-functions
index 536970b..53e6729 100644
--- a/public/variadic-functions
+++ b/public/variadic-functions
@@ -2,7 +2,7 @@
- Go by Example: Variadic Functions
+ Go в примерах: Функции с переменным числом аргументов (Variadic Functions)
@@ -172,7 +34,7 @@ to form closures, which we’ll look at next.
diff --git a/public/waitgroups b/public/waitgroups
index d8c3f13..11682c0 100644
--- a/public/waitgroups
+++ b/public/waitgroups
@@ -2,7 +2,7 @@
- Go by Example: WaitGroups
+ Go в примерах: WaitGroups
In this example we’ll look at how to implement
-a worker pool using goroutines and channels.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
packagemain
-
-
-
-
-
-
-
-
-
-
-
-
import(
- "fmt"
- "time"
-)
-
-
-
-
-
-
-
-
Here’s the worker, of which we’ll run several
-concurrent instances. These workers will receive
-work on the jobs channel and send the corresponding
-results on results. We’ll sleep a second per job to
-simulate an expensive task.
Here we send 5 jobs and then close that
-channel to indicate that’s all the work we have.
-
-
-
-
-
forj:=1;j<=5;j++{
- jobs<-j
- }
- close(jobs)
-
-
-
-
-
-
-
-
Finally we collect all the results of the work.
-This also ensures that the worker goroutines have
-finished. An alternative way to wait for multiple
-goroutines is to use a WaitGroup.
-
-
-
-
-
fora:=1;a<=5;a++{
- <-results
- }
-}
-
-
-
-
-
-
-
-
-
-
-
-
Our running program shows the 5 jobs being executed by
-various workers. The program only takes about 2 seconds
-despite doing about 5 seconds of total work because
-there are 3 workers operating concurrently.
-
-
-
-
-
$time go run worker-pools.go
-worker 1 started job 1
-worker 2 started job 2
-worker 3 started job 3
-worker 1 finished job 1
-worker 1 started job 4
-worker 2 finished job 2
-worker 2 started job 5
-worker 3 finished job 3
-worker 1 finished job 4
-worker 2 finished job 5
-
@@ -223,7 +34,7 @@ there are 3 workers operating concurrently.
diff --git a/public/writing-files b/public/writing-files
index 2969c77..fd622c1 100644
--- a/public/writing-files
+++ b/public/writing-files
@@ -2,7 +2,7 @@
- Go by Example: Writing Files
+ Go в примерах: Запись файлов (Writing Files)
@@ -287,7 +34,7 @@ we’ve just seen to the stdin and stdout streams.
diff --git a/public/xml b/public/xml
index e463b37..95f1a49 100644
--- a/public/xml
+++ b/public/xml
@@ -2,7 +2,7 @@
- Go by Example: XML
+ Go в примерах: XML
Go offers built-in support for XML and XML-like
-formats with the encoding.xml package.
+
Go предлагает встроенную поддержку XML и
+XML-подобных форматов с пакетом encoding.xml.
@@ -42,7 +42,7 @@ formats with the encoding.xml package.
-
+
packagemain
@@ -66,13 +66,12 @@ formats with the encoding.xml package.
-
This type will be mapped to XML. Similarly to the
-JSON examples, field tags contain directives for the
-encoder and decoder. Here we use some special features
-of the XML package: the XMLName field name dictates
-the name of the XML element representing this struct;
-id,attr means that the Id field is an XML
-attribute rather than a nested element.
+
Этот тип будет сопоставлен с XML. Как и в примерах JSON,
+теги полей содержат директивы для кодера и декодера.
+Здесь мы используем некоторые особенности пакета XML:
+XMLName определяет имя элемента XML, представляющего
+эту структуру; id,attr означает, что поле Id является
+атрибутом XML, а не вложенным элементом.
@@ -119,9 +118,9 @@ the name of the XML element representing this struct;
-
Emit XML representing our plant; using
-MarshalIndent to produce a more
-human-readable output.
+
Создаем XML, представляющий наш plant;
+использование MarshalIndent для создания более
+читабельного вывода.
@@ -135,8 +134,8 @@ human-readable output.
-
To add a generic XML header to the output, append
-it explicitly.
+
Чтобы добавить общий заголовок XML к выводу, добавьте
+его явно.
@@ -149,10 +148,10 @@ it explicitly.
-
Use Unmarhshal to parse a stream of bytes with XML
-into a data structure. If the XML is malformed or
-cannot be mapped onto Plant, a descriptive error
-will be returned.
+
Используйте Unmarhshal для парсинга байтов с XML в
+структуру данных. Если XML имеет неправильный формат
+или не может быть преобразован в Plant, будет
+возвращена описательная ошибка.
@@ -182,8 +181,9 @@ will be returned.
-
The parent>child>plant field tag tells the encoder
-to nest all plants under <parent><child>...
+
Поле parent>child>plant сообщает кодировщику о
+необходимости вложения всех plant в
+<parent><child>...
@@ -272,7 +272,7 @@ to nest all plants under <parent><child>...
- Next example: Time.
+ Следующий пример: Время (Time).
- Go is an
- open source programming language designed for
- building simple, fast, and reliable software.
+ Go - это язык программирования с
+ открытым исходным кодом, предназначенный для создания простого,
+ быстрого и надежного программного обеспечения.
- Go by Example is a hands-on introduction
- to Go using annotated example programs. Check out
- the first example or
- browse the full list below.
+ Go в примерах Go by Example - это практическое введение
+ в Go с использованием примеров реальных программ. Проверьте
+ первый пример или просмотрите полный
+ список ниже.