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.
The Go Programming Language Specification
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()
}