How to Convert Interface{} to String in Go

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

Golang time to string

Golang int to string

Golang bool to string

Golang int64 to string

Golang rune to string

Golang struct to string