How to Convert Interface{} to String in Go

To convert an interface{} to a string in Go, you can use the “.(string)” type assertion. The type assertions can cause panic if the underlying value is not of the specified type. To avoid this, you can use the two-value type assertion, which returns a boolean value indicating whether the assertion was successful.

Example 1

package main

import (
  "fmt"
)

func main() {
  var value interface{}
  value = "Script, story, logic, commonsense"

  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 a string: Script, story, logic, commonsense

In this code example, if the underlying value of the value variable is not a string, the program will not panic, and the ok variable will be false.

If you are sure that the interface value is a string, you can use the single-value type assertion, but be aware that it may cause a panic if the underlying value is not a string.

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.

Leave a Comment