Golang interface to string conversion possible? [SOLVED]


Written By - Tuan Nguyen
Advertisement

In one of our earlier posts, we previously went into great detail about the golang interface. With the aid of some relevant examples, we will examine how to convert data type interface to string in this post.

 

Golang interface{} to string with Type assertions

In general GO does not support conversion from interface{} to string. But one way to achieve this is using Type Assertion which allows you to test if a value stored in an interface variable is of a particular type. The type assertion returns two values: the underlying value and a result indicating whether the assertion succeeded.

For example, the following statement asserts that x is not nil and that the value stored in x is of type T:

x.(T)

Here is an example of using Type assertions to convert interface{} to string

package main

import "fmt"

func main() {
	// create an interface{}
	var str interface{} = "this is a string"

	//convert interface{} to string
	strConv2 := str.(string)

	// print out the result
	fmt.Printf("%T, %v\n", strConv2, strConv2)

}

Output:

string, this is a string

As mentioned, if the type assertion is false, a run-time panic occurs. The following example shown below will demonstrate that error:

package main

import "fmt"

func main() {
	// create an interface{}
	var str interface{} = []int{4, 5, 6, 7, 9}

	//convert interface{} to string
	strConv2 := str.(string)

	// print out the string
	fmt.Printf("%T, %v\n", strConv2, strConv2)

}

Output:

panic: interface conversion: interface {} is []int, not string

goroutine 1 [running]:
main.main()
        C:/Users/H518272/Desktop/go/test1.go:10 +0x66
exit status 2

 

Use fmt.Sprintf to convert an interface value to a string

func Sprintf(format string, a ...any) string: Sprintf formats according to a format specifier and returns the resulting string. We will use Sprintf() with %v format:

Advertisement
%v	the value in a default format
	when printing structs, the plus flag (%+v) adds field names

Example:

package main

import "fmt"

func main() {
	// create an interface{}
	var str interface{} = "this is a string"

	//convert interface{} to string
	strConv2 := fmt.Sprintf("%v", str)

	// print out the string
	fmt.Printf("%T, %v\n", strConv2, strConv2)

}

Output:

string, this is a string

Unlike Type assertion, with Sprintf() function, we can cast interface{} with any data type to string, consider the below example:

package main

import "fmt"

func main() {
	// create an interface{}
	var str interface{} = []int{4, 5, 6, 7, 9}

	//convert interface{} to string
	strConv2 := fmt.Sprintf("%v", str)

	// print out the string
	fmt.Printf("%T, %v\n", strConv2, strConv2)

}

Output:

string, [4 5 6 7 9]

 

Use for loop with fmt.Sprintf to convert interface values to string

If our interface contains multiple values then we can iterate over individual values and concert each one of them using fmt.Sprintf and storing them into slice.

package main

import (
	"fmt"
)

func main() {
	t := []interface{}{
		"blue",
		1, 2.0, 3.14,
		[]int{4, 5},
		struct{ X, Y int }{6, 7},
	}
	// Print interface content
	fmt.Println(t)
	// Print original type before conversion
	fmt.Printf("Original Type: %T\n", t)

	// Create empty slice based on length of interface
	s := make([]string, len(t))
	// Iterate over interface and convert each value to string
	for i, v := range t {
		s[i] = fmt.Sprint(v)
	}

	// Print slice content
	fmt.Println(s)
	// Print type after conversion
	fmt.Printf("Type: %T\n", s)
	fmt.Printf("%q\n", s)
}

Output:

[blue 1 2 3.14 [4 5] {6 7}]
Original Type: []interface {}
[blue 1 2 3.14 [4 5] {6 7}]
Type: []string
["blue" "1" "2" "3.14" "[4 5]" "{6 7}"]

 

Summary

In this article, I have given 2 examples of casting interface{} to string value. It's important to keep in mind that if the type assertion is incorrect, a run-time panic will occur so we can not cast an int or float64 interface{} to string value.

 

References

https://go.dev/ref/spec#Type_assertions
https://pkg.go.dev/fmt#Sprintf
https://go.dev/ref/spec#Interface_types
https://go.dev/ref/spec#Type_parameter_declarations
https://go.dev/ref/spec#Type_identity

 

Categories GO

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 either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment