go-tutorial

Go Structures

You can use Go arrays to create variables that can hold many data items of the same kind. Another user-defined data type in Go programming is structure, which allows you to mix data items of various types.

A record is represented using structures. Consider keeping track of the books in a library. You might want to keep track of the following book characteristics:

  • Title
  • Author
  • Subject
  • Book ID

Structures are really important in this situation.

Defining a Structure

You must use type and struct statements to define a structure. The struct statement creates a new data type for your programme with numerous members. The type statement associates a name with a type, which in our case is struct. The struct statement has the following format:

type struct_variable_type struct {

 member definition; member
 definition; ... member definition;
}

Once a structure type has been specified, the following syntax can be used to declare variables of that type.

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

Accessing Structure Members

The member access operator is used to access any member of a structure (.). The member access operator is a period between the name of the structure variable and the name of the structure member we want to access. The struct keyword is used to define variables of the structure type. The example below demonstrates how to use a structure.

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)
}

When the above code is compiled and executed, it produces the following result −

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

RECOMMENDED ARTICLES





Leave a Reply

Your email address will not be published.