go - 在 Go 中定义一个带有 channel 的接口(interface)

标签 go

我可以在 Go 中定义一个带有 channel 的接口(interface)吗?我想定义一个接口(interface),允许我使用不同类型的对象,这些对象都定义了相同的 channel 。执行:

type I interface {
    chan Communications []byte
    otherMethod()
}

(这给出语法错误:意外的 token 陈。我尝试了几种不同的语法和一些谷歌搜索无济于事。)

最佳答案

接口(interface)不保存数据,它定义了实现的内容。

您可以有一个返回 channel 的方法。例如:

type I interface {
    getChannel() (chan []byte)
    otherMethod()
}

请阅读接口(interface)。 tour会有帮助。

关于go - 在 Go 中定义一个带有 channel 的接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47796079/

相关文章:

go - Conn 在 Go 中随机关闭且没有警告

go - 相当于go中python的ord()、chr()?

Golang Websocket 自定义 JSON 消息

go - 无法在没有解析错误的情况下在 Google go 中添加时间

variables - 如何通过包共享变量

SublimeLinter 的 GoType 问题

go - 隐藏标志中的选项

mongodb - 我如何将 bson.M 元素列表组合成单个 bson.M 在 golang 的 mongo 中?

google-app-engine - Go app 在本地运行良好,运行 goapp serve 时产生 404

Go 中的递归