How to convert interface to string in Go
Created
Modified
Using fmt.Sprintf Function
To convert interface to string in Go, use fmt.Sprintf function.
Sprintf formats according to a format specifier and returns the resulting string.
package main
import "fmt"
var x = []interface{}{
"abc",
1,
3.14,
[]int{1, 2, 3},
struct {
A int
B string
}{
A: 10,
B: "code",
},
}
func main() {
// Method fmt.Sprintf("value: %v", v)
for _, v := range x {
str := fmt.Sprintf("%v", v)
fmt.Println(str)
}
// Method fmt.Sprint(v)
for _, v := range x {
str := fmt.Sprint(v)
fmt.Println(str)
}
}
abc 1 3.14 [1 2 3] {10 code} abc 1 3.14 [1 2 3] {10 code}
fmt.Sprint(val) is equivalent to fmt.Sprintf("%v", val)
If the %v verb is used with the # flag (%#v) and the operand implements the GoStringer interface, that will be invoked.
// Method fmt.Sprintf("value: %#v", v)
for _, v := range x {
str := fmt.Sprintf("%#v", v)
fmt.Println(str)
}
"abc" 1 3.14 []int{1, 2, 3} struct { A int; B string }{A:10, B:"code"}
Type Assertion
A type assertion provides access to an interface value's underlying concrete value.
package main
import "fmt"
func main() {
var i interface{} = "golang"
// Method t := i.(T)
s := i.(string)
fmt.Println(s)
// Method t, ok := i.(T)
s, ok := i.(string)
fmt.Println(s, ok)
f := i.(float64) // panic
fmt.Println(f)
}
golang golang true panic: interface conversion: interface {} is string, not float64
If i does not hold a T, the statement will trigger a panic.