Menu Close

Convert interface to string in Go

You can convert an interface to string in Go using the fmt.Sprint or fmt.Sprintf function.

Here is a example of converting an interface to string:

	var test interface{} = "stringInInterface"
	example1 := fmt.Sprint(test)
	example2 := fmt.Sprintf("%v", test) // allows to additionally format the string output

This approach works for any type. It is especially useful when working with JSON. When no struct representation of a JSON document is defined you can use a map[string]interface to decode the JSON data into a Go object. You can then convert the interface{} to String to get the value of a field in the JSON document:

func main() {
	var jsonObj map[string]interface{}
	jsonDoc := `{"foo0":"bar0","foo1":{"a":"1"}}`

	json.Unmarshal([]byte(jsonDoc), &jsonObj)

	stringFoo0 := fmt.Sprint(jsonObj["foo0"])

	// you can also access string within the nested object
	nestedObj, ok := jsonObj["foo1"].(map[string]interface{})
	if ok {
		stringFoo1a := fmt.Sprint(nestedObj[a])

Convert interface to string using type assertion

You can also convert an interface to a string using type assertion. This technique only works if the object referenced by the interface is realy a string:

	var test interface{} = "test"
	t, ok := test.(string) // if ok is false the type of the object reference is no string