convert Archives - Welcome To Golang By Example https://vikasboss.github.io/tag/convert/ Mon, 09 Mar 2020 23:43:34 +0000 en-US hourly 1 https://wordpress.org/?v=6.8.1 https://i0.wp.com/golangbyexamples.com/wp-content/uploads/2021/05/cropped-go_border-1.png?fit=32%2C32&ssl=1 convert Archives - Welcome To Golang By Example https://vikasboss.github.io/tag/convert/ 32 32 159787465 Interface to struct in Go (Golang) https://vikasboss.github.io/interface-to-struct/ https://vikasboss.github.io/interface-to-struct/#respond Mon, 18 Mar 2019 16:38:18 +0000 https://vikasboss.github.io/?p=73 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...

The post Interface to struct in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
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: "xyz@gmail.com"}
	convert(newCustomer)
}

func convert(event interface{}) {
	c := NewCustomerEvent{}
	mapstructure.Decode(event, &c)
	fmt.Printf("Event is: %v", c)
}

Output:

Event is: {x 082213909101 xyz@gmail.com}

The post Interface to struct in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
https://vikasboss.github.io/interface-to-struct/feed/ 0 73