How to convert string to interface in Golang?
December 08, 2022Hi Friends 👋,
Welcome To aGuideHub! ❤️
In Go, you can convert a string to an interface by first using the json.Unmarshal()
function to convert the string to a map[string]interface{}
value, and then using a type assertion to convert the map value to the desired interface type.
Here is an example of how to convert a string to an interface in Go:
package main
import (
"fmt"
"encoding/json"
)
type MyInterface interface {
SomeMethod()
}
type MyType struct {
SomeField string
}
func (t *MyType) SomeMethod() {}
func main() {
jsonData := []byte(`{"SomeField": "Hello World"}`)
// convert the JSON string to a map
var m map[string]interface{}
err := json.Unmarshal(jsonData, &m)
if err != nil {
panic(err)
}
// convert the map to the MyType type
var i MyInterface
i = &MyType{
SomeField: m["SomeField"].(string),
}
fmt.Println(i)
}
In this example, we have an interface type called MyInterface
and a type called MyType
that implements this interface. We then create a JSON string and use the json.Unmarshal()
function to convert it to a map[string]interface{}
value.
Next, we use a type assertion to convert the map value to the MyType type, which allows us to create a value of type MyInterface that contains the data from the original JSON string.
You can use this technique to convert any string to an interface in Go.
Output:
&{Hello World}
All the best 👍