Golang type conversion summary

There are 4 types of type-conversions in Go:

  • Assertion.
  • Forced type conversion.
  • Explicit type conversion.
  • Implicit type conversion.

Commonly said type conversion refers to assertion, forced type conversion is not used in daily life, explicit is a basic type conversion, implicitly used but not noticed.

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.

Assertion Type Conversion.

Asserts by judging whether a variable can be converted to a certain type.

Note: Type assertions can only happen on interfaces.

Let’s first look at a simple assertion expression.

var s = x.(T)

If x is not nil, and x can be converted to type T, the assertion succeeds, and a variable s of type T is returned.

If T is not an interface type, the type of x is required to be T, and if T is an interfacex is required to implement the T interface.

If the assertion type is true, the return value of the expression is x of type T, and panic will be triggered if the assertion fails.

If the assertion fails, it will panic. Go provides another assertion syntax with the return:

s, ok := x.(T)

This method is almost the same as the first one, but ok will return whether the assertion is successful without panic, and ok indicates whether it is successful.

Click Here