通过一个通道在不同的Go包/文件之间发送和接收数据

huangapple go评论111阅读模式
英文:

Send and receive data through one channel on different Go package/file

问题

你可以创建两个Go源代码文件,并通过一个通道发送或接收数据,就像上面的图像/插图描述的那样。因此,在源代码运行时,这些文件可以通过发送数据来相互通信。

英文:
+----------------+                       +-----------------+
| Channel foo    |                       | Channel foo     |
| a.go           |                       | b.go            |
+----------------+                       +-----------------+
       |                                          |
       |__________________________________________|
        Send or receive data through 'foo' channel

Can I create two Go source code files and send or receive data through one channel such as described from image/illustration above? So, these files could communicate each other with sending data while source code is running.

答案1

得分: 7

通道(Channels)只是Go语言中的变量,就像int[]bytebool一样。如果你可以在包之间传递任何变量,那么显然你也可以在包之间传递通道。一旦你将一个通道从一个包传递到另一个包,你当然可以在那里自由地使用它,就像使用任何其他变量一样。这意味着你可以在一个包中发送数据,在另一个包中接收数据。

如果通道不能在包之间共享,那么它们将不会非常有用。

英文:

Channels are just variables in Go, like int, []byte or bool. If you can pass any variables between packages, you can obviously then pass channels between packages as well. And once you've passed a channel from one package to another, you are of course free to use it there, just as you would any other variable. That means you can send data in one package, and receive it in another.

Ultimately channels wouldn't be very useful if they couldn't be shared between packages.

huangapple
  • 本文由 发表于 2017年6月21日 15:32:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/44669550.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定