how to convert one struct to another in golang?

Hi Friends 👋,

Welcome To aGuideHub! ❤️

To convert one struct to another in golang, just use type definer it will convert one struct to another. Only you have to write new struct type with old value.


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 one struct to another in golang, as above mentioned I’m going to use type definer way.

Let’s start our Golang convert one struct to another example

main.go

package main

import "fmt"

type type1 []struct {
	Field1 string
	Field2 int
}
type type2 []struct {
	Field1 string
	Field2 int
}

func main() {
	t1 := type1{{"A", 1}, {"B", 2}}
	t2 := type2(t1)
	fmt.Println(t2)
}

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

Output

[{A 1} {B 2}]

I hope it helps you, All the best 👍.

Follow me on Twitter