Thumbnail article
Data Conversion in Golang
Data conversion is used to change the data type of a variable containing data values into the data type required. The following describes the types of conversions found in Golang:
  1. Convert using strconv
    • strconv.Atoi()This function is used to convert data from string to int type. strconv.Atoi() produces 2 return values, namely the conversion result and an error (if the conversion is successful, then the error contains nil). The following code is an example of implementing strconv.Atoi():
      package main
      
      import "fmt"
      import "strconv"
      
      func main() {
      	var s = "123"
      	var n, err = strconv.Atoi(s)
      
      	if err == nil {
      		fmt.Println(n)
      	}
      }
      
      Output :
    • strconv.Itoa()Is the opposite of strconv.Atoi, useful for converting int to string. The following code is an example of implementing strconv.Itoa():
      package main
      
      import "fmt"
      import "strconv"
      
      func main() {
      	var b = 123
      	var s = strconv.Itoa(b)
      
      	fmt.Println(s)
      }
      
      Output :
    • strconv.ParseInt()Used to convert a numeric string with a specified base to a non-decimal numeric type with a specified data width. The following code is an example of implementing strconv.ParseInt():
      package main
      
      import "fmt"
      import "strconv"
      
      func main() {
      	var s = "123"
      	var b, err = strconv.ParseInt(s, 10, 64)
      	if err == nil {
      		fmt.Println(b)
      	}
      }
      
      Output : In the program code, the data value “123” with a specified string type with a numeric base of 10, will be converted to an int64 data type.
    • strconv.FormatInt()This function is used to convert int64 numeric data to a string with a numeric base that can be defined by yourself. The following code is an example of implementing strconv.FormatInt():
      package main
      
      import "fmt"
      import "strconv"
      
      func main() {
      	var b = int64(10)
      	var s = strconv.FormatInt(b, 8)
      	fmt.Println(s)
      }
      
      Output :
    • strconv.ParseFloat()Used to convert a string to a decimal numeric with a specified data width. The result of the conversion of strconv.ParseFloat is in accordance with the IEEE Standard for Floating-Point Arithmetic. The following code is an example of implementing strconv.ParseFloat():
      package main
      
      import "fmt"
      import "strconv"
      
      func main() {
      	var s = "12.3"
      	var b, err = strconv.ParseFloat(s, 32)
      	if err == nil {
      		fmt.Println(b)
      	}
      }
      
      Output :
    • strconv.FormatFloat()Used to converting data of type float64 to string with exponential format, decimal digit width, and data type width can be specified. There are several exponential formats that can be used, including:
      1. b   :  -ddddp±ddd, a, binary exponent (base 2).
      2. e   : -d.dddde±dd, a, decimal exponent (base 10).
      3. E  :  -d.ddddE±dd, a, decimal exponent (base 10).
      4. f   : -ddd.dddd, without exponent.
      5. g  : Will use the exponent format e for large exponents and f for others.
      6. G : Will use the exponent format E for large exponents and f for anything else.
      The following code is an example of implementing strconv.FormatFloat():
      package main
      
      import "fmt"
      import "strconv"
      
      func main() {
      	var b = float64(12.3)
      	var s = strconv.FormatFloat(b, 'f', 6, 64)
      	fmt.Println(s)
      }
      
      Output : In the program code, the data value in variable b is “12.3” which is of type float64, then converted into a string data type with the exponential format f (without exponents), the range of decimal digits is 6 digits, and the width of data type is float64.
    • strconv.ParseBool()Used for string to bool conversion. The following code is an example of implementing strconv.ParseBool():
      package main
      
      import "fmt"
      import "strconv"
      
      func main() {
      	var s = "true"
      	var bo, err = strconv.ParseBool(s)
      	if err == nil {
      		fmt.Println(bo)
      	}
      }
      
      Output :
    • strconv.FormatBool()Used for bool to string conversion. The following code is an example of implementing strconv.FormatBool():
      package main
      
      import "fmt"
      import "strconv"
      
      func main() {
      	var bo = true
      	var s = strconv.FormatBool(bo)
      	fmt.Println(s)
      }
      
      Output :
  2. Data Conversion using Casting TechniqueData type keywords can be used for casting, or conversion between data types. How to use it is to write the data type of the casting destination as a function, then insert the data to be converted as a parameter of the function.Casting string ↔ byteStrings are actually slices/arrays of bytes. In Go a regular character (not unicode) is represented by a byte slice element. Each slice element contains an int data with a decimal base, which is the ASCII code of the character in the string.The way to get a byte slice from a data string is to use Casting to type [] bytes. Each byte element contains numeric data with a decimal base. The following is an example of a string in the variable t converted to [] bytes. Each element of the byte slice is then displayed individually.The following code is an example of implementing casting string ↔ byte:
    package main
    
    import "fmt"
    
    func main() {
    	var t = "Garudabyte"
    	var b = []byte(t)
    
    	fmt.Printf("%d %d %d %d %d %d %d %d %d %d", 
    	b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7], b[8], b[9])
    }
    
    Output : The following code is an example of implementing casting byte ↔ string:
    package main
    
    import "fmt"
    
    func main() {
    	var b = []byte{71, 97, 114, 117, 100, 97, 98, 121, 116, 101}
    	var str = string(b)
    
    	fmt.Printf("%s \n", str)
    }
    
    Output : In the sample program code, some byte code is written as a series of slices, which are accommodated by the variable b. Then, the value of the variable is converted (cast) into a string data type and then displayed with the command fmt.Printf(“%s \n”, s).
  3. Conversion of Data interface{} using Type Assertions TechniqueType assertions are a technique for retrieving concrete data types from data wrapped in interface{}. So it can be concluded that the type assertions technique can only be performed on data of interface{} type.We must first know what the original data type of the data stored in the interface. If you don’t know,  you can use a switch – case combination to detect concrete types of interface{} data.The following code is an example of implementing type assertions:
    package main
    
    import "fmt"
    
    func main() {
    	var n = map[string]interface{}{
    		"name":"Joana",
    		"grade":7.5,
    		"class":8,
    		"isMale":false,
    	}
    
    	fmt.Println(n["name"].(string))
    	fmt.Println(n["grade"].(float64))
    	fmt.Println(n["class"].(int))
    	fmt.Println(n["isMale"].(bool))
    }
    
    Output : Prepared variable n type map[string]interface{} with values ​​of different data types. The statement n[“name”].(string) means that n[“name”] is being cast as a string. The original data type of the interface{} variable can be determined by casting interface{} to type. However, this casting can only be done on a switch.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *