English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
You can also use a pointer tostructof the pointer. Golang's struct (structure) is a user-defined type that allows grouping items of possibly different types/Combined into a single type. To use a pointer to the structure, you can use&Operator, that is, the address operator. Golang allows programmers to access the fields of the structure without explicitly dereferencing.
Example1:Here, we create a structure named Employee with two variables. In the main function, create an instance of the structure, i.e., emp, and then, you can pass the address of the structure to a pointer representing the concept of the structure. There is no need to explicitly dereference it, as it will give the same result as the following program (twice ABC).
package main import "fmt" //Define the structure type Employee struct { //Set field name string empid int {} func main() { //The instance created //Employee structure type emp := Employee{"ABC", 19078{} //Here, it refers to a pointer to the structure pts := &emp fmt.Println(pts) //Accessing structure field (employee's name) //Using a pointer, but here we did not use explicit dereferencing fmt.Println(pts.name) //By explicitly using dereferencing //This represents the same result as above fmt.Println(*.name) {}
Output:
&{ABC 19078{} ABC ABC
Example2:You can also use pointers to modify the value of structure members or structure literals as shown below:
package main import "fmt" //Define the structure type Employee struct { name string empid int {} func main() { //The instance created //Employee structure type emp := Employee{"ABC", 19078{} //Here, it refers to a pointer to the structure pts := &emp //Display the value fmt.Println(pts) //Update the value of name pts.name = "XYZ" fmt.Println(pts) {}
Output:
&{ABC 19078{} &{XYZ 19078{}