英文:
Confusion about Go syntax
问题
在这种情况下,c.(*TCPConn) 是一种类型断言(type assertion)操作。它将变量 c 断言为 *TCPConn 类型,并返回两个值:tc 和 ok。
tc 是一个指向 *TCPConn 类型的指针,表示将 c 转换为 *TCPConn 类型后的结果。ok 是一个布尔值,表示类型断言是否成功。
在这段代码中,如果类型断言成功,即 c 是 *TCPConn 类型的实例,那么就会执行一些与 TCP 连接相关的操作,比如设置 KeepAlive 和 KeepAlivePeriod。如果类型断言失败,那么 ok 的值将为 false,代码块中的操作将被跳过。
你可以在 这里 的第 171 行找到这段代码的源代码。
希望这能帮助你理解这段代码的作用。如果还有其他问题,请随时提问!
英文:
I seen this in the net package source code on golang.org.
c, err := dial(network, ra.toAddr(), dialer, d.deadline())
if d.KeepAlive > 0 && err == nil {
if tc, ok := c.(*TCPConn); ok {
tc.SetKeepAlive(true)
tc.SetKeepAlivePeriod(d.KeepAlive)
testHookSetKeepAlive()
}
}
return c, err
What is c.(*TCPConn) doing exactly in this case? I thought initially it was some kind of type casting, but it returns 2 values to tc and ok.
This is confusing to me. Can someone explain what this code is doing please?
source code here line 171.
答案1
得分: 7
《Go编程语言规范》中的内容如下:
类型断言(Type assertions)用于判断一个接口类型的表达式x是否为非nil,并且存储在x中的值的类型是否为T。类型断言的语法为x.(T)。
在赋值或初始化的特殊形式中使用类型断言:
v, ok = x.(T)
v, ok := x.(T)
var v, ok = x.(T)
这样会产生一个额外的无类型布尔值。如果断言成立,ok的值为true。否则,ok的值为false,v的值为类型T的零值。
如果c是类型为Conn的接口类型,并且包含一个类型为TCPConn的值,那么ok的值为true,并且tc被设置为c中存储的TCPConn类型的值。c也可能包含nil、*UDPConn、*UnixConn等。在这种情况下,tc将为nil,ok将为false。
示例代码如下:
if tc, ok := c.(*TCPConn); ok {
tc.SetKeepAlive(true)
tc.SetKeepAlivePeriod(d.KeepAlive)
testHookSetKeepAlive()
}
你可以在以下链接中找到更多关于Go编程语言规范的信息:
英文:
> The Go Programming Language Specification
>
> Type assertions
>
> For an expression x of interface type and a type T, the primary
> expression
>
> x.(T)
>
> asserts that x is not nil and that the value stored in x is of type T.
> The notation x.(T) is called a type assertion.
>
> A type assertion used in an assignment or initialization of the
> special form
>
> v, ok = x.(T)
> v, ok := x.(T)
> var v, ok = x.(T)
>
> yields an additional untyped boolean value. The value of ok is true if
> the assertion holds. Otherwise it is false and the value of v is the
> zero value for type T.
If c of type Conn, an interface type, contains a value of type *TCPConn then ok is true and tc is set to the value of type *TCPConn stored in c. c could also contain nil, *UDPConn, *UnixConn, et cetera. In which case, tc will be nil and ok will be false.
if tc, ok := c.(*TCPConn); ok {
tc.SetKeepAlive(true)
tc.SetKeepAlivePeriod(d.KeepAlive)
testHookSetKeepAlive()
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论