Go Programming Language Structures - Go (programming language)

What is a Structure in Go programming language?

A user defined data type which enables to combine different kinds of data items facilitated by Go programming language is called as Structure.

A record is represented using Structures. For instance, to track a book in the library the attributes that are to be tracked about each book are:

  • Title
  • Author
  • Subject
  • Book ID

Define a Structure

Type and struct statements are used to define a Structure. A new data type with more than one member is defined by struct for the program, and type statement binds a name with the typoe which is struct. The format of the struct statement is:

Structure type is used to declare the variables of that type by the syntax:

How to access Structure Members?

member access operator (.) is used to access any member of the structure. A period between the structure variable name and the structure member is coded by the member access operator. Variables of the structure type are defined by the struct keyword.

An illustration on the usage of Structure is:

When the above code is compiled and executed, the result produced appears as -

How to pass a Structure as Function Argument?

In a way any variable or pointer is passed as a function argument, even the structure is passed as a function argument. Structure variables are accessed in the similar way as shown in the above example:

When the above code is compiled and executed, the result produced appears as -

How to define Pointers to Structures?

As pointers are defined to any other variables, in the same way, pointers are defined to structures, as follows:

In the above defined pointer variable, store the address of the structure variable. By placing the & operator before the structure's name, the address of the structure variable can be found, as follows:

To access the members of a structure using a pointer to that structure, use the "." operator as follows:

The above example is re-written using structure pointer:

When the above code is compiled and executed, the result produced appears as -

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Go (programming language) Topics