how to convert interface to string in golang?
August 28, 2022Hi Friends 👋,
Welcome To aGuideHub! ❤️
To convert interface to string in golang, use fmt.Sprintf(v)
method, it will convert interface to string. You have to only pass your interface or interface elements value in fmt.Sprintf()` method.
Follow the below tutorial if you are struggling with installing GO in windows.
https://aguidehub.com/blog/how-to-install-golang-in-windows/
Today, I will show you how do I convert a interface to string in golang, as above mentioned I’m going to use fmt.Sprintf(v)
method.
To use the fmt.Sprintf(v)
method, we have first import "fmt"
package, then we have to pass our interface value with in fmt.Sprintf(v)
method.
Let’s start our Golang convert interface to string example
main.go
package main
import "fmt"
func main() {
fmt.Println("Make string whole interface")
var x interface{} = []int{1, 2, 3}
xStr := fmt.Sprint(x)
fmt.Println(xStr)
fmt.Println("Make string interface elements")
var testValues = []interface{}{
"test",
2,
3.2,
[]int{1, 2, 3, 4, 5},
struct {
A string
B int
}{
A: "A",
B: 5,
},
}
for _, v := range testValues {
valStr := fmt.Sprint(v)
fmt.Println(valStr)
}
}
In the above example, we have converted the interface value to a strig and printed in golang console. let’s check the output.
Output
Make string whole interface
[1 2 3]
Make string interface elements
test
2
3.2
[1 2 3 4 5]
{A 5}
I hope it helps you, All the best 👍.