gpt4 book ai didi

go - 关于 Go 语法的困惑

转载 作者:IT王子 更新时间:2023-10-29 01:22:00 25 4
gpt4 key购买 nike

我在 golang.org 的 net 包源代码中看到了这一点。

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

在这种情况下,c.(*TCPConn) 到底在做什么?我最初以为这是某种类型转换,但它返回 2 个值给 tcok

这让我很困惑。有人可以解释这段代码的作用吗?

source code here第 171 行。

最佳答案

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.

如果接口(interface)类型 Connc 包含类型 *TCPConn 的值,则 ok为真并且 tc 被设置为 *TCPConn 类型的值存储在 c 中。 c 还可以包含 nil*UDPConn*UnixConn 等。在这种情况下,tc 将为 nilok 将为 false。

if tc, ok := c.(*TCPConn); ok {
tc.SetKeepAlive(true)
tc.SetKeepAlivePeriod(d.KeepAlive)
testHookSetKeepAlive()
}

关于go - 关于 Go 语法的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29596518/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com