Golang type conversion summary

<p>There are 4 types of&nbsp;<code>type-conversions</code>&nbsp;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&nbsp;<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&nbsp;<code>interfaces</code>.</p> <p>Let&rsquo;s first look at a simple assertion expression.</p> <pre> var s = x.(T)</pre> <p>If&nbsp;<code>x</code>&nbsp;is not&nbsp;<code>nil</code>, and&nbsp;<code>x</code>&nbsp;can be converted to type&nbsp;<code>T</code>, the assertion succeeds, and a variable&nbsp;<code>s</code>&nbsp;of type&nbsp;<code>T</code>&nbsp;is returned.</p> <p>If&nbsp;<code>T</code>&nbsp;is not an&nbsp;<code>interface</code>&nbsp;type, the type of&nbsp;<code>x</code>&nbsp;is required to be&nbsp;<code>T</code>, and if&nbsp;<code>T</code>&nbsp;is an&nbsp;<code>interface</code>,&nbsp;<code>x</code>&nbsp;is required to implement the&nbsp;<code>T</code>&nbsp;interface.</p> <p>If the assertion type is&nbsp;<code>true</code>, the return value of the expression is&nbsp;<code>x</code>&nbsp;of type&nbsp;<code>T</code>, and&nbsp;<code>panic</code>&nbsp;will be triggered if the assertion fails.</p> <p>If the assertion fails, it will&nbsp;<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&nbsp;<code>ok</code>&nbsp;will return whether the assertion is successful without&nbsp;<code>panic</code>, and&nbsp;<code>ok</code>&nbsp;indicates whether it is successful.</p> <p><a href="https://levelup.gitconnected.com/golang-type-conversion-summary-dc9e36842d25">Click Here</a></p>