Go - Estructuras

Los arreglos Go le permiten definir variables que pueden contener varios elementos de datos del mismo tipo. Structure es otro tipo de datos definido por el usuario disponible en la programación Go, que le permite combinar elementos de datos de diferentes tipos.

Las estructuras se utilizan para representar un registro. Suponga que desea realizar un seguimiento de los libros de una biblioteca. Es posible que desee realizar un seguimiento de los siguientes atributos de cada libro:

  • Title
  • Author
  • Subject
  • ID del libro

En tal escenario, las estructuras son muy útiles.

Definición de una estructura

Para definir una estructura, debe utilizar type y structdeclaraciones. La declaración de estructura define un nuevo tipo de datos, con varios miembros para su programa. La declaración de tipo une un nombre con el tipo que es struct en nuestro caso. El formato de la declaración de estructura es el siguiente:

type struct_variable_type struct {
   member definition;
   member definition;
   ...
   member definition;
}

Una vez que se define un tipo de estructura, se puede usar para declarar variables de ese tipo usando la siguiente sintaxis.

variable_name := structure_variable_type {value1, value2...valuen}

Acceso a miembros de estructura

Para acceder a cualquier miembro de una estructura, usamos el member access operator (.).El operador de acceso a miembros se codifica como un período entre el nombre de la variable de estructura y el miembro de estructura al que deseamos acceder. Usaríasstructpalabra clave para definir variables de tipo de estructura. El siguiente ejemplo explica cómo utilizar una estructura:

package main

import "fmt"

type Books struct {
   title string
   author string
   subject string
   book_id int
}
func main() {
   var Book1 Books    /* Declare Book1 of type Book */
   var Book2 Books    /* Declare Book2 of type Book */
 
   /* book 1 specification */
   Book1.title = "Go Programming"
   Book1.author = "Mahesh Kumar"
   Book1.subject = "Go Programming Tutorial"
   Book1.book_id = 6495407

   /* book 2 specification */
   Book2.title = "Telecom Billing"
   Book2.author = "Zara Ali"
   Book2.subject = "Telecom Billing Tutorial"
   Book2.book_id = 6495700
 
   /* print Book1 info */
   fmt.Printf( "Book 1 title : %s\n", Book1.title)
   fmt.Printf( "Book 1 author : %s\n", Book1.author)
   fmt.Printf( "Book 1 subject : %s\n", Book1.subject)
   fmt.Printf( "Book 1 book_id : %d\n", Book1.book_id)

   /* print Book2 info */
   fmt.Printf( "Book 2 title : %s\n", Book2.title)
   fmt.Printf( "Book 2 author : %s\n", Book2.author)
   fmt.Printf( "Book 2 subject : %s\n", Book2.subject)
   fmt.Printf( "Book 2 book_id : %d\n", Book2.book_id)
}

Cuando el código anterior se compila y ejecuta, produce el siguiente resultado:

Book 1 title      : Go Programming
Book 1 author     : Mahesh Kumar
Book 1 subject    : Go Programming Tutorial
Book 1 book_id    : 6495407
Book 2 title      : Telecom Billing
Book 2 author     : Zara Ali
Book 2 subject    : Telecom Billing Tutorial
Book 2 book_id    : 6495700

Estructuras como argumentos de función

Puede pasar una estructura como un argumento de función de forma muy similar a como pasa cualquier otra variable o puntero. Accederá a las variables de estructura de la misma manera que lo hizo en el ejemplo anterior:

package main

import "fmt"

type Books struct {
   title string
   author string
   subject string
   book_id int
}
func main() {
   var Book1 Books    /* Declare Book1 of type Book */
   var Book2 Books    /* Declare Book2 of type Book */
 
   /* book 1 specification */
   Book1.title = "Go Programming"
   Book1.author = "Mahesh Kumar"
   Book1.subject = "Go Programming Tutorial"
   Book1.book_id = 6495407

   /* book 2 specification */
   Book2.title = "Telecom Billing"
   Book2.author = "Zara Ali"
   Book2.subject = "Telecom Billing Tutorial"
   Book2.book_id = 6495700
 
   /* print Book1 info */
   printBook(Book1)

   /* print Book2 info */
   printBook(Book2)
}
func printBook( book Books ) {
   fmt.Printf( "Book title : %s\n", book.title);
   fmt.Printf( "Book author : %s\n", book.author);
   fmt.Printf( "Book subject : %s\n", book.subject);
   fmt.Printf( "Book book_id : %d\n", book.book_id);
}

Cuando el código anterior se compila y ejecuta, produce el siguiente resultado:

Book title     : Go Programming
Book author    : Mahesh Kumar
Book subject   : Go Programming Tutorial
Book book_id   : 6495407
Book title     : Telecom Billing
Book author    : Zara Ali
Book subject   : Telecom Billing Tutorial
Book book_id   : 6495700

Punteros a estructuras

Puede definir punteros a estructuras de la misma manera que define punteros a cualquier otra variable de la siguiente manera:

var struct_pointer *Books

Ahora, puede almacenar la dirección de una variable de estructura en la variable de puntero definida anteriormente. Para encontrar la dirección de una variable de estructura, coloque el operador & antes del nombre de la estructura de la siguiente manera:

struct_pointer = &Book1;

Para acceder a los miembros de una estructura usando un puntero a esa estructura, debe usar el "." operador de la siguiente manera:

struct_pointer.title;

Reescribamos el ejemplo anterior usando el puntero de estructura -

package main

import "fmt"

type Books struct {
   title string
   author string
   subject string
   book_id int
}
func main() {
   var Book1 Books   /* Declare Book1 of type Book */
   var Book2 Books   /* Declare Book2 of type Book */
 
   /* book 1 specification */
   Book1.title = "Go Programming"
   Book1.author = "Mahesh Kumar"
   Book1.subject = "Go Programming Tutorial"
   Book1.book_id = 6495407

   /* book 2 specification */
   Book2.title = "Telecom Billing"
   Book2.author = "Zara Ali"
   Book2.subject = "Telecom Billing Tutorial"
   Book2.book_id = 6495700
 
   /* print Book1 info */
   printBook(&Book1)

   /* print Book2 info */
   printBook(&Book2)
}
func printBook( book *Books ) {
   fmt.Printf( "Book title : %s\n", book.title);
   fmt.Printf( "Book author : %s\n", book.author);
   fmt.Printf( "Book subject : %s\n", book.subject);
   fmt.Printf( "Book book_id : %d\n", book.book_id);
}

Cuando el código anterior se compila y ejecuta, produce el siguiente resultado:

Book title     : Go Programming
Book author    : Mahesh Kumar
Book subject   : Go Programming Tutorial
Book book_id   : 6495407
Book title     : Telecom Billing
Book author    : Zara Ali
Book subject   : Telecom Billing Tutorial
Book book_id   : 6495700