итерация в каналах

This commit is contained in:
badkaktus 2019-10-08 11:18:36 +03:00
parent c16c142918
commit 33465a0288
2 changed files with 11 additions and 12 deletions

View File

@ -1,7 +1,7 @@
// In a [previous](range) example we saw how `for` and // В [предыдущем](range) примере мы виделе как `for` и
// `range` provide iteration over basic data structures. // `range` позволяют перебирать базовые структуры. Мы
// We can also use this syntax to iterate over // так же можем использовать этот синтаксис для чтения
// values received from a channel. // значений из канала.
package main package main
@ -9,16 +9,16 @@ import "fmt"
func main() { func main() {
// We'll iterate over 2 values in the `queue` channel. // Мы будем итерировать 2 значения в канале `queue`.
queue := make(chan string, 2) queue := make(chan string, 2)
queue <- "one" queue <- "one"
queue <- "two" queue <- "two"
close(queue) close(queue)
// This `range` iterates over each element as it's // Этот `range` будет перебирать каждый элемент
// received from `queue`. Because we `close`d the // полученный из канала `queue`. Но т.к. мы `закрыли`
// channel above, the iteration terminates after // канал ранее, перебор элементов завершится после
// receiving the 2 elements. // получения двух элементов.
for elem := range queue { for elem := range queue {
fmt.Println(elem) fmt.Println(elem)
} }

View File

@ -2,6 +2,5 @@ $ go run range-over-channels.go
one one
two two
# This example also showed that it's possible to close # Этот пример так же демонстрирует, что возможно
# a non-empty channel but still have the remaining # прочитать данные из канала уже после его закрытия.
# values be received.