⚙️ Convert interface to string in Go
·1 min
To convert interface to string in Go, use fmt.Sprint function, which gets the default string representation of any value. If you want to format an interface using a non-default format, use fmt.Sprintf with %v verb.
fmt.Sprint(val)is equivalent tofmt.Sprintf("%v", val)
package main
import "fmt"
var testValues = []interface{}{
"test",
2,
3.2,
[]int{1, 2, 3, 4, 5},
struct {
A string
B int
}{
A: "A",
B: 5,
},
}
func main() {
// method 1
fmt.Println("METHOD 1")
for _, v := range testValues {
valStr := fmt.Sprint(v)
fmt.Println(valStr)
}
// method 2
fmt.Printf("\nMETHOD 2\n")
for _, v := range testValues {
valStr := fmt.Sprintf("value: %v", v)
fmt.Println(valStr)
}
}
Output:
METHOD 1
test
2
3.2
[1 2 3 4 5]
{A 5}
METHOD 2
value: test
value: 2
value: 3.2
value: [1 2 3 4 5]
value: {A 5}
Alternatively, you can use the %+v verb to add field names to struct representation:
test
2
3.2
[1 2 3 4 5]
{A:A B:5}
or use %#v to format value in the Go-syntax style:
"test"
2
3.2
[]int{1, 2, 3, 4, 5}
struct { A string; B int }{A:"A", B:5}