Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/opencv/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Go 为什么频道不工作?_Go - Fatal编程技术网

Go 为什么频道不工作?

Go 为什么频道不工作?,go,Go,我正在学习“Go并发模式” 问题: 渠道如何从外部共享变量?在这种情况下,我被分享了。 点A和点B的变量似乎有某种特殊的关系?这是什么 这对你意味着什么 对于i:=0;i++ 主要代码: package main import ( "fmt" "math/rand" "time" ) func boring(msg string) <-chan string { // Returns receive-only channel of strings. c

我正在学习“Go并发模式”

问题:

渠道如何从外部共享变量?在这种情况下,我被分享了。 点A和点B的变量似乎有某种特殊的关系?这是什么

这对你意味着什么

对于i:=0;i++

主要代码:

package main

import (
    "fmt"
    "math/rand"
    "time"
)

func boring(msg string) <-chan string { // Returns receive-only channel of strings.

    c := make(chan string)
    go func() { // We launch the goroutine from inside the function.
        for i := 0; ; i++ {           // <--------- point B
            c <- fmt.Sprintf("%s %d", msg, i)

            time.Sleep(time.Duration(rand.Intn(1e3)) * time.Millisecond)
        }
    }()
    return c // Return the channel to the caller.
}

func main() {
    c := boring("boring!") // Function returning a channel.
    for i := 0; i < 5; i++ {               // <--------- point A
        fmt.Printf("You say: %q\n", <-c)
    }
    fmt.Println("You're boring; I'm leaving.")
}
i的最大值:=0;i++{}创建一个永远递增的索引


当您创建CHAN字符串时,您已经创建了一个读/写通道。您还可以在go函数中引用通道,并将其作为返回值传递出去。Go对变量的使用方式进行分析,称为escape analysis,并选择是在堆上还是在堆栈上创建通道(以堆为例),以便在创建通道的函数退出时,通道不会被释放。

您到底是如何运行此操作的?你知道,Go不是一种脚本语言。您需要编译程序并使用go run运行它。而且,它不能是包a1,如果要运行它,它必须是包a1main@Not_a_Golfer我通过更改包名解决了这个问题。谢谢但我不知道它是如何工作的……首先:通道不会导致变量之间的神奇连接或变量共享。实际上,通道与变量无关。通道所做的是:它们把你塞进通道的值,然后在另一端吐出相同的值。这些值通常来自变量,并且这些变量通常具有相同或相似的名称。第二:你提到的for you循环类似于C语言。看看这类基本问题的教程或语言规范。@Volker我想我已经找到答案了。在点B,goroutine无限填充int值,1…n。然后A点,一个接一个地说出来!但仍然不能确定“阻塞”的顺序……也不能确定无限循环是如何工作的。我的意思是它懒惰吗?几乎。点B只是一个for循环;递增的整数值填充到c处的通道中
You say: "boring! 0"
You say: "boring! 1"
You say: "boring! 2"
You say: "boring! 3"
You say: "boring! 4"
You're boring; I'm leaving.
Program exited.