在 Go 中使用结构体中的接口
在试图理解 Go 的过程中,我在 websocket.go
中遇到了这段代码(被剪掉了):
type frameHandler interface {
HandleFrame(frame frameReader) (r frameReader, err error)
WriteClose(status int) (err error)
}
// Conn represents a WebSocket connection.
type Conn struct {
config *Config
request *http.Request
.
.
frameHandler
PayloadType byte
defaultCloseStatus int
}
在 Conn 类型中,frameHandler
是单独存在的吗?没有名字的接口? 后来在代码中,他们甚至尝试检查不良接口是否为零:
Conn(a).frameHandler == nil
我自己的猜测是,结构中的frameHandler是与frameHandler接口匹配的类型,最重要的是,该类型将具有名称frameHandler
。这是正确的吗?呵呵,无论如何,有趣的语言。
In trying to understand Go, I ran into this piece of code in websocket.go
(snipped):
type frameHandler interface {
HandleFrame(frame frameReader) (r frameReader, err error)
WriteClose(status int) (err error)
}
// Conn represents a WebSocket connection.
type Conn struct {
config *Config
request *http.Request
.
.
frameHandler
PayloadType byte
defaultCloseStatus int
}
In the Conn type the frameHandler
stands there all alone? An interface without a name?
Later on in the code they even try check if the poor interface is nil:
Conn(a).frameHandler == nil
My own guess is that the frameHandler
within the struct is a type which matches the frameHandler interface, and on top of that will have the name frameHandler
. Is this correct? Hehe, fun language anyhow.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这一行:
大致相当于:
frameHandler
既是字段的名称,又是其类型。此外,它还将frameHandler
的所有字段和方法添加到Conn
中,因此如果conn
是一个Conn
>,则conn.WriteClose(0)
表示conn.frameHandler.WriteClose(0)
。正如 Go 编程语言规范 所说:
This line:
is roughly equivalent to this:
in that
frameHandler
is both the name of the field and its type. In addition, it adds all the fields and methods of theframeHandler
to theConn
, so ifconn
is aConn
, thenconn.WriteClose(0)
meansconn.frameHandler.WriteClose(0)
.As the Go Programming Language Specification puts it: