关于Go语法的困惑

huangapple go评论84阅读模式
英文:

Confusion about Go syntax

问题

在这种情况下,c.(*TCPConn) 是一种类型断言(type assertion)操作。它将变量 c 断言为 *TCPConn 类型,并返回两个值:tcok

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编程语言规范的信息:

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()
}

huangapple
  • 本文由 发表于 2015年4月13日 09:09:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/29596518.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定