Golang cast to string from different data types [SOLVED]


GOLANG Solutions, GO

Golang cast to string from multiple data types

In golang we have multiple data types such as string, int, interface, boolean, float etc. In this article, we shall be discussing how to convert different data types into strings using type casting with help of practical examples. A string is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding. For example "GoLinuxCloud" is a string represented by the following characters G,o,L,i,n,u,x,C,l,o,u,d.

Different data types can be converted into string, Below are area of focus in this article:-

  • Convert Int type to string in Golang
  • Convert Interface type to string in Golang
  • Convert Boolean type to string in Golang

 

Convert Int type to string in Golang

The integer represents an array of numerical data types such as int, int32, int64, etc.
We can easily convert values of int data type into string using Golang standard package known as strconv.Int to string conversion can happen in the following ways using strconv package function and fmt standards:-

  • Using Sprintf() from fmt packages
  • Using Itoa() from strconv
  • Using FormatInt() from strconv

 

Method 1:- Convert int to string using Sprintf()

In Golang we can easily convert an integer to a string is to use the fmt.Sprintf function from fmt package. The function formats according to a format specifier and returns the resulting string.

Example

package main

import (
	"fmt"
)

func main() {
	var res int64 = 3
	results := fmt.Sprintf("The value is %d of type %T, converted to a string is %v", res, res, res)
	println(results)
}

Output:-

$ go run main.go 
The value is 3 of type int64, converted to a string is 3

 

Method 2:- Convert int to string using Itoa()

We shall be using strconv.Itoa() from Golang standard package, it just accepts one input value of type int, and returns a string. The general syntax to be used here is func Itoa(i int) string:

Example

package main

import (
	"fmt"
	"reflect"
	"strconv"
)

func main() {
	var res = 20
	fmt.Println(res, reflect.TypeOf(res))
	str := strconv.Itoa(res)
	fmt.Println(str, reflect.TypeOf(str))
}

Output:=

$ go run main.go
20 int
20 string

Explanation: In the above code we are using reflect package to print out the data type of the variable. we then convert the variable value into string using Itoa() method.

 

Method 3:- Convert int to string using FormatInt()

Using Golang strconv standard package provides us with strconv.FormatInt() which accepts a values of int64 and base of 2 <= base <= 36, which returns a string representation of base if value is greater or equal to 10. The returned values are in aligned with the ASCII(American Standard Code for Information Interchange) string. The general syntax to be used here is func FormartInt(i int64, base int) string:

Example

package main

import (
	"fmt"
	"reflect"
	"strconv"
)

func main() {
	var res int64 = 2334444
	fmt.Println(res, reflect.TypeOf(res))
	str := strconv.FormatInt(res, 10)
	fmt.Println(str, reflect.TypeOf(str))
}

Output:=

$ go run main.go
2334444 int64
2334444 string

Explanation:- In the code above, we have declare a variable of type int64 var res int64 = 2334444 the variable is in desired format of int64 by the strconv.FormatInt(), we pass it to the function to process values into string. The reflect package is used to print the type of value as well.

 

Convert Interface type to string in Golang

In Golang, an interface is a custom type that is used to specify a set of one or more method signatures. This set can be the string "" or and an array of the same data type. We can easily convert Interface values into string using Golang fmt standard package, this package provides fmt.Sprintf() function which converts the values into string.

Example of interface value conversion to string

package main

import "fmt"

func main() {
	// interface of an array of string data type

	var val interface{} = []string{"Gmail", "Chrome", "Microsoft", "GoLinuxCloud"}
	// interface  of strings
	var str interface{} = "Hello GoLinuxCloud"

	results := fmt.Sprintf("Results of Array:  %v \nResults of String data: %v", val, str)
	println(results)
}

Output:

$ go run main.go 
Results of Array:  [Gmail Chrome Microsoft GoLinuxCloud] 
Results of String data: Hello GoLinuxCloud

Explanation: Using fmt.Sprintf() function can combine several data types into one variable. We have managed to convert an interface of string and array using one variable. This so because the fmt.Sprintf() function accepts string and a variadic of interface or ellipsis of interface values.

 

Convert Boolean type to string in Golang

Boolean is true or false statement, In Golang we can convert this boolean type into string using Golang standard packages such as fmt and strconv packages. These two packages offer us with following functions to help in boolean to string conversion such as fmt package fmt.Sprint() which accepts arguments of string type and an interface and returns formatted string type as results, and the strconv package offers strconv.FormatBool() it accepts boolean arguments i.e true or false and returns a string "true" or "false".

Below is a practical example of the conversion of boolean values into a string.

 

Example 1: Using fmt.Sprintf() function

package main

import (
	"flag"
	"fmt"
)

func main() {
	// by default if no arguments passed if false
	val := flag.Bool("plaintext", false, "Enable plaintext")
	flag.Parse()
	res := fmt.Sprintf("%v", *val)
	fmt.Printf("Data Type: %T \n Value converted to  is %v\n", val, res)
}

Output:=

$ go run main.go -plaintext=1   
Data Type: *bool 
 Value converted to  is true

Explanation: In the array of boolean 0 represent false and 1 represent true. Using flag package recognizes the two digits as boolean. We can use them to pass true or false value. We are using Pass by the pointer of values to be converted into a string.

 

Example 2: using strconv.FormatBool() function

package main

import (
	"flag"
	"fmt"
	"strconv"
)

func convertBoolToString(val bool) string {
	return strconv.FormatBool(val)
}
func main() {
	// by default if no arguments passed if false
	Val := flag.Bool("plaintext", false, "Enable plaintext")
	flag.Parse()
	res := convertBoolToString(*val)
	fmt.Printf("Data Type: %T \n Value converted to is %v\n", Val, res)
}

Output when the -plaintext=true

$ go run main.go -plaintext=true
Data Type: *bool 
 Value converted to is true

when the no -plaintext=value. If no value is attached it will be false as the default value using the flag package.

$ go run main.go 
Data Type: *bool 
 Value converted to is false

Explanation: We are using the flags package to read users' arguments to validate the attached value to be of type boolean only. It accepts 1, 2, true or false only values. We can pass the pointer of that variable to our function for conversion.

 

Summary

Data type conversion is a key area in the Golang application program. In this article, we have highlighted various ways to convert int, interface, and boolean data type into string. This so helpful when reading user inputs from any aspects of application development level.

 

References

type conversion

 

Deepak Prasad

Deepak Prasad

He is the founder of GoLinuxCloud and brings over a decade of expertise in Linux, Python, Go, Laravel, DevOps, Kubernetes, Git, Shell scripting, OpenShift, AWS, Networking, and Security. With extensive experience, he excels in various domains, from development to DevOps, Networking, and Security, ensuring robust and efficient solutions for diverse projects. You can connect with him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment