Golang type conversion summary
<p>There are 4 types of <code>type-conversions</code> in Go:</p>
<ul>
<li>Assertion.</li>
<li>Forced type conversion.</li>
<li>Explicit type conversion.</li>
<li>Implicit type conversion.</li>
</ul>
<p>Commonly said type conversion refers to <code>assertion</code>, forced type conversion is not used in daily life, explicit is a basic type conversion, implicitly used but not noticed.</p>
<p>The three categories of assertion, force, and explicit are all explained in the Go syntax description, and the implicit is summarized in the daily use process.</p>
<p><strong>Assertion Type Conversion.</strong></p>
<p>Asserts by judging whether a variable can be converted to a certain type.</p>
<p>Note: Type assertions can only happen on <code>interfaces</code>.</p>
<p>Let’s first look at a simple assertion expression.</p>
<pre>
var s = x.(T)</pre>
<p>If <code>x</code> is not <code>nil</code>, and <code>x</code> can be converted to type <code>T</code>, the assertion succeeds, and a variable <code>s</code> of type <code>T</code> is returned.</p>
<p>If <code>T</code> is not an <code>interface</code> type, the type of <code>x</code> is required to be <code>T</code>, and if <code>T</code> is an <code>interface</code>, <code>x</code> is required to implement the <code>T</code> interface.</p>
<p>If the assertion type is <code>true</code>, the return value of the expression is <code>x</code> of type <code>T</code>, and <code>panic</code> will be triggered if the assertion fails.</p>
<p>If the assertion fails, it will <code>panic</code>. Go provides another assertion syntax with the return:</p>
<pre>
s, ok := x.(T)</pre>
<p>This method is almost the same as the first one, but <code>ok</code> will return whether the assertion is successful without <code>panic</code>, and <code>ok</code> indicates whether it is successful.</p>
<p><a href="https://levelup.gitconnected.com/golang-type-conversion-summary-dc9e36842d25">Click Here</a></p>