Cookies management by TermsFeed Cookie Consent

⚙️ Convert interface to string in Go

introduction interface strings

Please consider supporting us by disabling your ad blocker

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 to fmt.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}

Thank you for being on our site 😊. If you like our tutorials and examples, please consider supporting us with a cup of coffee and we'll turn it into more great Go examples.

Have a great day!

🍒 Concatenate strings in Go

Learn the differences between string concatenation methods
introduction strings

🖨️ Convert string to []byte or []byte to string in Go

Learn the difference between a string and a byte slice
introduction strings slice

🔟 Convert string to bool in Go

Learn how to parse a string as a bool
introduction strings bool