how to convert interface to struct in golang?

Hi Friends 👋,

Welcome To aGuideHub! ❤️

To convert interface to struct in golang, use interface.(Struct) method, it will convert interface to struct. You have to only pass your struct type in interface.


Follow the below tutorial if you are struggling with installing GO in windows.

https://aguidehub.com/blog/how-to-install-golang-in-windows/


Today, I will show you how do I convert a interface to struct in golang, as above mentioned I’m going to use interface.(Struct) method.

Let’s start our Golang convert interface to struct example

main.go

package main

import "fmt"

type User struct {
	id int
	name  string
}

func main() {
	user := User{
		id: 1,
		name:  "aGuideHub",
	}

	convert(user)
}

func convert(object interface{}) {
	user, ok := object.(User)

	if ok {
		fmt.Printf("Hello %s!\n", user.name)
	}
}

In the above example, we have converted the interface value to a struct and printed in golang console. let’s check the output.

Output

Hello aGuideHub!

I hope it helps you, All the best 👍.

Try it Yourself

Premium Content

You can get all the below premium content directly in your mail when you subscribe us

Books

Interview Questions

Soon You will get CSS, JavaScript, React Js, and TypeScript So Subscribe to it.

Portfolio Template

View | Get Source Code

Cheat Sheets

Cheat Sheets Books are basically Important useful notes which we use in our day-to-day life.

Related Posts