What does 'sconn, ok:= conn.(*tls.Conn)' mean?

Issue

I encountered an statement ** sconn, ok:= conn.(*tls.Conn) ** in some guy’s code.
I guess it’s some kind of type conversion? conn is type of net.Conn. This can convert conn to *tls.Conn

I am not sure what does it mean. What’s this grammar mean?

Solution

It tries to assert that conn (which presumably has an interface type) is a *tls.Conn (presumably a type that satisfies the interface) and assign (if the value underlying the interface-typed value) the (now *tls.Conn) to sconn. If it is the correct underlying type, the ok variable will contain the boolean true, otherwise the boolean false.

https://golang.org/ref/spec#Type_assertions

Answered By – Vatine

Answer Checked By – David Goodson (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.