英文:
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
、[]byte
或bool
一样。如果你可以在包之间传递任何变量,那么显然你也可以在包之间传递通道。一旦你将一个通道从一个包传递到另一个包,你当然可以在那里自由地使用它,就像使用任何其他变量一样。这意味着你可以在一个包中发送数据,在另一个包中接收数据。
如果通道不能在包之间共享,那么它们将不会非常有用。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论