How to Copy Struct Type Using Value and Pointer Reference in Golang?
A structure or struct in Golang is a user-defined data type that allows to combine data types of different kinds and act as a record.
A struct variable in Golang can be copied to another variable easily using the assignment statement(=). Any changes made to the second struct will not be reflected back to the first struct.
Example 1:
// Golang program to illustrate copying // a structure to another variable package main import ( "fmt" ) // declaring a structure type Student struct { // declaring variables name string marks int64 stdid int64 } // main function func main() { // creating the instance of the // Student struct type std1 := Student{ "Vani" , 98, 20024} // prints the student struct fmt.Println(std1) // copying the struct student // to another variable by // using the assignment operator std2 := std1 // printing copied struct // this will have same values // as struct std1 fmt.Println(std2) // changing values of struct // std2 after copying std2.name = "Abc" std2.stdid = 20025 // printing updated struct fmt.Println(std2) } |
Output:
{Vani 98 20024} {Vani 98 20024} {Abc 98 20025}
In the case of pointer reference to the struct, the underlying memory location of the original struct and the pointer to the struct will be the same. Any changes made to the second struct will be reflected in the first struct also. Pointer to a struct is achieved by using the ampersand operator(&). It is allocated on the heap and its address is shared.
Example 2:
// Golang program to illustrate the // concept of a pointer to a struct package main import ( "fmt" ) // declaring a structure type Person struct { // declaring variables name string address string id int64 } // main function func main() { // creating the instance of the // Person struct type p1 := Person{ "Vani" , "Delhi" , 20024} // prints the student struct fmt.Println(p1) // referencing the struct person // to another variable by // using the ampersand operator // Here, it is the pointer to the struct p2 := &p1 // printing pointer to the struct fmt.Println(p2) // changing values of struct p2 p2.name = "Abc" p2.address = "Hyderabad" // printing updated struct fmt.Println(p2) // struct p1 values will // also change since values // of p2 were also changed fmt.Println(p1) } |
Output:
{Vani Delhi 20024} &{Vani Delhi 20024} &{Abc Hyderabad 20024} {Abc Hyderabad 20024}
Please Login to comment...