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:
package main
import (
"fmt"
)
type Student struct {
name string
marks int64
stdid int64
}
func main() {
std1 := Student{ "Vani" , 98, 20024}
fmt.Println(std1)
std2 := std1
fmt.Println(std2)
std2.name = "Abc"
std2.stdid = 20025
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:
package main
import (
"fmt"
)
type Person struct {
name string
address string
id int64
}
func main() {
p1 := Person{ "Vani" , "Delhi" , 20024}
fmt.Println(p1)
p2 := &p1
fmt.Println(p2)
p2.name = "Abc"
p2.address = "Hyderabad"
fmt.Println(p2)
fmt.Println(p1)
}
|
Output:
{Vani Delhi 20024}
&{Vani Delhi 20024}
&{Abc Hyderabad 20024}
{Abc Hyderabad 20024}