SoFunction
Updated on 2025-03-05

A brief discussion on golang's pitfalls

Recently, I encountered a pitfall during golang business development.

We have a service that will receive a common interface object and then send a message to the user. Therefore, it involves converting the strings passed by each business party into interface objects.

But because there is a number in my string, such as the following demo{"number":1234567}, and the number is 7 digits, after passingLater, it was converted into the form of scientific notation, resulting in an abnormality in the link sent by the private message, and an error was reported.

package main

import (
   "encoding/json"
   "fmt"
)

func main() {
   jsonStr := `{"number":1234567}`
   result := make(map[string]interface{})
   err := ([]byte(jsonStr), &result)
   if err != nil {
      (err)
   }
   (result) // map[number:1.234567e+06]

}

When the data structure is unknown, usemap[string]interface{}When receiving the deserialization result, if the number of digits is greater than 6 digits, it will become a scientific notation method and the places used will be affected.

fromencoding/jsonIn the package, you can find the following comment:

//
// To unmarshal JSON into an interface value,
// Unmarshal stores one of these in the interface value:
//
// bool, for JSON booleans
// float64, for JSON numbers
// string, for JSON strings
// []interface{}, for JSON arrays
// map[string]interface{}, for JSON objects
// nil for JSON null
//

For numbers, they will be parsed intofloat64Type, there may be a scientific notation form.

Problem Solution 1: Casting Type Conversion

func main() {
   jsonStr := `{"number":1234567}`
   result := make(map[string]interface{})
   err := ([]byte(jsonStr), &result)
   if err != nil {
      (err)
   }
   (int(result["number"].(float64)))

   // Output   // 1234567
}

Problem Solution 2: Try to avoid usinginterface,rightjsonString structure definition structure

func main() {
   type Num struct {
      Number int `json:"number"`
   }

   jsonStr := `{"number":1234567}`
   var result Num
   err := ([]byte(jsonStr), &result)
   if err != nil {
      (err)
   }
   (result)

   // Output   // {1234567}
}

Reference documentation:https:///article/

This is the end of this article about the pitfalls of golang. For more related golang content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!