How to Convert Interface to Struct in Golang

To convert an Interface to a Struct in Golang, you can use the interface.(Struct) method.Type assertion lets you “specify the desired type and returns the value in that type if the assertion holds”.

If the underlying value isn’t of the specified type, it will panic unless you use the two-value form.

package main

import "fmt"

type Student struct {
  Name string
  Age int
}

func main() {
  var mainInterface interface{} = Student{Name: "Krunal", Age: 30}

  // Convert interface to struct using type assertion
  student, ok := mainInterface.(Student)
  if !ok {
    fmt.Println("Conversion failed")
    return
  }
  fmt.Printf("Name: %s, Age: %d\n", student.Name, student.Age)
}

Output

Name: Krunal, Age: 30

That’s it!

Related posts

Go struct to json

Go map to struct

Go struct to string

Go interface to struct

Go string to json

Go interface to string