Como punteros son las variables especiales que se utilizan para almacenar la dirección de memoria de otra variable, mientras que la estructura es un tipo de datos definido por el usuario que consta de diferentes tipos. Una estructura es principalmente un contenedor para todos los demás tipos de datos. Al usar un puntero a una estructura, podemos manipular/acceder fácilmente a los datos asignados a una estructura. Para usar el puntero a una estructura, usamos «&», es decir, el operador de dirección . En Go lang, mediante el uso de punteros a una estructura podemos acceder a los campos de una estructura sin desreferenciarlos explícitamente.
Ejemplo: aquí hemos definido los nombres de una estructura como «forma» y estamos pasando los valores al campo de esta estructura. Además, estamos imprimiendo el valor de la estructura usando punteros.
Go
// Golang program to show how to instantiate // Struct Pointer Address Operator package main import "fmt" type shape struct { length int breadth int color string } func main() { // Passing all the parameters var shape1 = &shape{10, 20, "Green"} // Printing the value struct is holding fmt.Println(shape1) // Passing only length and color value var shape2 = &shape{} shape2.length = 10 shape2.color = "Red" // Printing the value struct is holding fmt.Println(shape2) // Printing the length stored in the struct fmt.Println(shape2.length) // Printing the color stored in the struct fmt.Println(shape2.color) // Passing only address of the struct var shape3 = &shape{} // Passing the value through a pointer // in breadth field of the variable // holding the struct address (*shape3).breadth = 10 // Passing the value through a pointer // in color field of the variable // holding the struct address (*shape3).color = "Blue" // Printing the values stored // in the struct using pointer fmt.Println(shape3) }
Producción:
&{10 20 Green} &{10 0 Red} 10 Red &{0 10 Blue}