How to Convert Interface to Struct in Golang

To convert an Interface to Struct in Golang, you can use the type assertion” or “type switch”.

Method 1: Using Type assertion

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.

Example

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

Method 2: Using the Type switch

Type switch allows “you to check multiple types simultaneously and perform actions based on the underlying type”.

Example

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 switch
  switch value := mainInterface.(type) {
    case Student:
      fmt.Printf("Name: %s, Age: %d\n", value.Name, value.Age)
    default:
      fmt.Println("Unknown type")
  }
}

Output

Name: Krunal, Age: 30

Choose the method that best suits your use case. For example, type assertion is more concise when you know exactly which type you expect, while type switch is more versatile when you have multiple possible types.

Leave a Comment