How to Fix cannot convert data (type interface {}) to type string: need type assertion

To fix the cannot convert data (type interface {}) to type string: need type assertion error in Go, you need to perform a type assertion from interface{} to string. For example, if you have a var data interface{}, you must perform a type assertion using data.(string) expression.

Golang raises the error “cannot convert data (type interface {}) to type string: need type assertion” when you’re trying to convert a value of the interface{} type to the string type without using a type assertion.

package main

import (
  "fmt"
)

func main() {
  var data interface{}
  data = "Hello, world!"

  // Try to directly assign data to a string variable
  // without type assertion

  str := data
  fmt.Println("The string value is:", str)
}

Output

cannot use data (type interface {}) as type string in assignment:
need type assertion

To fix this error, perform a type assertion. For example, the interface{} type in Go is an empty interface that can hold any value, but to use the underlying value with its actual type, you need to perform a type assertion.

A type assertion provides access to the concrete value of an interface value.

package main

import (
  "fmt"
)

func main() {
  var data interface{}
  data = "Lathiya, Krunal!"

  if str, ok := data.(string); ok {
    fmt.Println("The string value is:", str)
  } else {
    fmt.Println("Type assertion failed.")
  }
}

Output

The string value is: Lathiya, Krunal!

In this example, we have an interface{} variable data containing a string value. To access the string value, we perform a type assertion using the syntax data.(string). This operation returns two values: the actual string value (if the assertion is successful) and a boolean value ok, suggesting whether the type assertion succeeded or not.

If the type assertion fails (e.g., the underlying value is not a string), ok will be false, and you should handle this case appropriately.

Remember that type assertion can cause a runtime panic if they fail and you don’t use the two-value form with the ok boolean. Always use the two-value form to perform type assertions and handle potential failures safely.

That’s it.

Leave a Comment