Welcome To Golang By Example

Menu
  • Home
  • Blog
Menu

Interface to struct in Go (Golang)

Posted on March 18, 2023March 9, 2023 by admin

We come around a situation sometimes in programming where an empty interface might a struct internally and we have to get the concrete struct out of it. Whoever is not aware of what an empty interface is should read this excellent article: https://research.swtch.com/interfaces.

For conversion of interface{} to a struct, we will use the library – https://github.com/mitchellh/mapstructure . Let’s understand how to convert the interface to a struct by an example:

package main
import (
"fmt"
"github.com/mitchellh/mapstructure"
)
type NewCustomerEvent struct {
Name string
Phone string
Email string
}
func main() {
newCustomer := NewCustomerEvent{Name: "x", Phone: "082213909101", Email: "[email protected]"}
convert(newCustomer)
}
func convert(event interface{}) {
c := NewCustomerEvent{}
mapstructure.Decode(event, &c)
fmt.Printf("Event is: %v", c)
}

Output:

Event is: {x 082213909101 [email protected]}
  • convert
  • go
  • interface
  • struct
  • Popular Articles

    Golang Comprehensive Tutorial Series

    All Design Patterns in Go (Golang)

    Slice in golang

    Variables in Go (Golang) – Complete Guide

    OOP: Inheritance in GOLANG complete guide

    Using Context Package in GO (Golang) – Complete Guide

    All data types in Golang with examples

    Understanding time and date in Go (Golang) – Complete Guide

    ©2024 Welcome To Golang By Example | Design: Web XP