SoFunction
Updated on 2025-03-05

Detailed explanation of the Go type conversion tool library cast function

1. What is cast

cast is an open source tool library on Github. Just like his name, it provides us with very convenientType conversionmethod.

We can pull the cast library through the following address:

go get /spf13/cast

2. Two APIs

The cast library provides us with two commonly used APIs:as well as(xxx is the data type to be converted into).

When returning the converted value, aerrorThe bottom layer is rightIt was encapsulated and abandonederrorreturn value.

The cast library implements rich and intuitive type conversion encapsulation for us to()As an example:

   ("mayonegg")         // "mayonegg"
   (8)                  // "8"
   (8.31)               // "8.31"
   ([]byte("one time")) // "one time"
   (nil)                // ""

   var foo interface{} = "one more time"
   (foo)                // "one more time"

We can intuitively observe,()A lot of intuitive conversion situations are considered to help us get String from various data types.

for()The same goes for:

   (8)                  // 8
   (8.31)               // 8
   ("8")                // 8
   (true)               // 1
   (false)              // 0

   var eight interface{} = 8
   (eight)              // 8
   (nil)                // 0

()Even helped us think about iteightTurn to8The situation.

In addition to basic data types, the cast library also provides us with similarToStringMapStringConvert container data type method.

3. Source code analysis

In this part, we use two sets of source code as examples to analyze the underlying implementation of cast:

  • ToStringMapE
func ToStringMapE(i interface{}) (map[string]interface{}, error) {
   var m = map[string]interface{}{}

   switch v := i.(type) {
   case map[interface{}]interface{}:
      for k, val := range v {
         m[ToString(k)] = val
      }
      return m, nil
   case map[string]interface{}:
      return v, nil
   case string:
      err := jsonStringToObject(v, &m)
      return m, err
   default:
      return m, ("unable to cast %#v of type %T to map[string]interface{}", i, i)
   }
}

We can see that the underlying layer of cast is still implemented by type assertion + switch, which needs to be converted intomap[string]interface{}The demands ofToString()Methods for type conversion andjsonStringToObject()Methods to perform json analysis,ToString()The idea of ​​type transformation is similar, and the knowledge has taken into account more situations. I will not repeat it here. Next, we will focus on it.jsonStringToObject()Methods are simple to analyze.

  • ToString()
func jsonStringToObject(s string, v interface{}) error {
   data := []byte(s)
   return (data, v)
}

ToString()The method is called the Go-owned source()Method, perform the parsing of json strings, and bind the parsed map to m.

This is the end of this article about the detailed explanation of the cast function of the Go type conversion tool library. For more related Go cast content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!