To convert an interface{} to a string in Go, you can use the “fmt. Sprintf(v) function” or “.(string)” type assertion.
Method 1: Using fmt.Sprintf(v) function
Provide the value of your interface or its elements to fmt.Sprintf(v) function to get its string representation.
Example
package main
import (
"fmt"
)
func main() {
var value interface{}
value = "Script, story, logic, commonsense"
str := fmt.Sprintf("%v", value)
fmt.Println("Converted string:", str)
}
Output
Converted string: Script, story, logic, commonsense
Method 2: Using .(string) type assertion
In Go, interface{} is an empty interface that can hold any type. If you have an interface{} value and want to convert it to a string, you must first assert its type.
Example 1
package main
import (
"fmt"
)
func main() {
var value interface{}
value = "Script, story, logic, commonsense"
str, ok := value.(string)
if ok {
fmt.Println("Converted string:", str)
} else {
fmt.Println("The interface value is not a string.")
}
}
Output
Converted string: Script, story, logic, commonsense
Example 2
Let’s pass an integer and cause a panic.
package main
import (
"fmt"
)
func main() {
var value interface{}
value = 4
str := value.(string)
fmt.Println("The interface value is a string:", str)
}
Output
panic: interface conversion: interface {} is int, not string
You can see that the interface value is not a string, and that’s why the code created panic at runtime.
To fix the panic: interface conversion: interface {} is int, not string error, you can use the two-value type assertion.
package main
import (
"fmt"
)
func main() {
var value interface{}
value = 4
str, ok := value.(string)
if ok {
fmt.Println("The interface value is a string:", str)
} else {
fmt.Println("The interface value is not a string.")
}
}
Output
The interface value is not a string.
That’s it.
Related posts

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.