Go Structure


January 7, 2022, Learn eTutorial
1214

In this tutorial, we will be checking out the Go struct data type which falls under the aggregate data type of composite types. In this tutorial you will gain knowledge of what exactly is a structure in Golang, their definition and declaration syntax in Golang, naming a struct, accessing and nesting struct data types, etc.

What is a struct in Golang?

A struct is a structure composed of a collection of fields where each field holds different types of data. So, In Golang struct is categorized under aggregate type of composite data type. The fields defined within a struct have different properties & each property is of specified types and of assigned values.

  •     Struct is a collection of composite fields
  •     Struct allows the grouping of related data into a single unit/entity.
  •     Struct is a lightweight class without inheritance.
     

Eg: Consider an Employee database in an organization that keeps records related to all employees such as employee details like name, age, id, place, salary, etc. these are different fields that contain various types of data that refer to a single entity under struct data type.

PHP : Struct
  •    Name, Age, Place, Id, Salary fields are records of employee's details.
  •    Age, Id are types that store an integer type value
  •    Name, Salary are types that store string values.
  •    So the record of an employee is a combination/collection of fields of different types of entities under one structure

Defining a structure

To define a structure two keywords are required. They are

  1.    type: Allows to create a  new type that follows a struct name
  2.    struct: Represents the new data type
     

type emp_details struct{
Name string
Age int
Place string
Id int
Salary int
}

The above code shows a struct named emp_details with fields Name, Age, Place, Id, and Salary. The above struct defined is a named struct because it creates a new struct data type named emp_details.

  •    The keyword type mentions a new type & the keyword struct defines the type as structure. 
  •    The type the keyword is followed by the name of the structure (emp_details). 
  •    The struct contains a list of various fields such as name, age, place, salary, id of employees inside the curly braces. 
  •    Each field has a name and a type. 
  •    Example: Name is of type string, Salary is of type int so on.

Each field is written one per line which can be altered by grouping fields with similar data types to a single line as shown below:


type emp_details struct{
Name Place string  //single line declaration of same type(string)
Age Id Salary Int //single line declaration of same type(integer)
}

How to initialize a  Structure (struct) in Golang

In Go language, a struct is initialized by using var keyword or shorthand declaration using the symbol “:= ”.Whenever the struct fields are not initialized with any specific values they are set to default type.

Let’s understand one by one using an example

  1.    Initialization of struct fields using the var keyword
  2.    Initialization of struct fields using shorthand 
  3.    The default type is Zero if not initialized  while the declaration
     

Program 1. Initialization of struct fields using the var keyword


// Golang program to show how to declare and define the struct  
package main  
import "fmt"
  
// Defining a struct type
type emp_details struct {
    Name    string
    Age int
    Place string
    Id int
    salary int
}
  
func main() {
     // Declaring a variable  e  `struct` type using var keyword
     var e emp_details
     fmt.Println(e)
   
    //Declaring and Initializing variable of struct type
    var e1 = emp_details{"miya", 20,"Mumbai",0067,20000}
 fmt.Println(e1)
    
     //Declaring and Initializing variable of struct type
    var e2 = emp_details{Age: 10, salary: 45000} 
 fmt.Println(e2)
}

Output:


{ 0  0 0}
{miya 20 Mumbai 55 20000}
{ 10  0 45000}

Explanation

  •   Defined a struct type name emp_details.
  •   A variable e is declared followed by a struct name
  •   Var e emp_details
    PHP : Struct
  •  Created another variable e1 to which assigns or initialize values to struct fields by referring to the struct name
    PHP : Struct
  •  Created another variable e2 to which we can initialize values depending on the programmer's need. In a single line-specific selected field are initialized rest of the uninitialized values of fields will be set to default type. Strings are empty space while integer values are 0 during the default type.
    PHP : Struct

    Program 2: Initialization of struct fields using shorthand

    
    // Golang program to show how to declare and define the struct  
    package main  
    import "fmt"
      
    // Defining a struct type
    type emp_details struct {
        Name    string
        Age int
        Place string
        Id int
        salary int
    }
      
    func main() {
       
           // Shorthand notation Declaration and Initialization 
        e1 := emp_details{"miya", 20,"Mumbai",0067,20000}
     fmt.Println(e1)
        
         //Shorthand notation Declaration and Initialization
       e2 := emp_details{Age: 10, salary: 45000} 
     fmt.Println(e2)
    }
    
    

    Output:

    
    {miya 20 Mumbai 55 20000}
    { 10  0 45000}
    

Explanation

  •   Defined a struct type name emp_details.
  •   Same as we discussed in the above program but instead of the var keyword we used the syntax “:= “ to initialize values of the struct type. Just replaced var with:= syntax.
    PHP : Struct
  •  Output is also as same as the previous program.

    Program 3 Default type is Zero if not initialized while a declaration

    
    // Golang program to show how to  declare and define the struct  
    package main
    import "fmt"
    
     // Defining a struct type
    type emp_details struct {
        Name    string
        Age int
        Place string
        Id int
        salary int
    }  
    func main() {
    
    // Declaring a variable of a `struct` type
    // All the struct fields are initialized  with their zero value
    var e emp_details
    fmt.Println(e)
    }
    
    

    Output:

    
    { 0  0 0}
    

Explanation

  •   The above program creates a variable of a type emp_details which is by default set to zero.
  •   For a struct data type, zero means all the fields inside the structure are set to their corresponding zero value.
  •   So the fields Name, Place is set to “ ” (empty string) Age, Id, salary are set to 0.
     

Access struct field

In Golang Struct fields are accessed by a dot ( .) operator. Getting and setting struct fields are easy is Golang using the dot operator

In a below-given program created a struct emp_details that has 5 fields. To access & assign a value to the field Name of string type, we use syntax
 

PHP : Struct

Let’s understand with an example


// Golang program to show how to  declare and define the struct  
package main
import "fmt"
 // Defining a struct type
type emp_details struct {
    Name    string
    Age int
    Place string
    Id int
    salary int
}  
func main() {
  
    // Declaring a variable of a `struct` type
   // All the struct fields are initialized  with their zero value  
    var e emp_details
    //setting values using dot(.) operator
    e.Name = "Nainika"
    e.Age=5
    e.Place = "MALAYSIA"
    e.Id = 007
    e.salary = 100000
    //Displays output

Output:


 e.Name : Nainika
 e.Age : 5
 e.Place : MALAYSIA
 e.Id: 7
 e.salary : 100000

Golang embedded struct type

In Golang struct data type provides a property called embedding which enables embedding a struct inside another struct. A struct type can be defined as another struct type.

  •    Embedding a struct is also a kind of nesting struct.
  •    When two struct type is declared and one of the struct types defined make use of the parent struct type for initialization nesting of struct occurs.
  •    In the below syntax Address is a struct type nested inside another emp_details struct type
  •    After the declaration of a struct type, it is initialized using:=.
  •    In the below-given program, an emp variable is declared that uses emp_details struct type where there initialize its own fields like Name, Age and calls struct type Address to further use fields defined under it such as city, country.
     

Syntax


type Address struct {
    City    string
    Country string
}

type emp_details struct {
    Name string
    Age int
    Address
}


package main

import "fmt"

type Address struct {
    city    string
    country string
}

type emp_details struct {
    name string
    age  int
    Address
}

func main() {
    emp := emp_details{
        name: "Joseph",
        age:  54,
        Address: Address{
            city:    "italy",
            country: "USA",
        },
    }

    fmt.Println("Name of employee:", emp.name)
    fmt.Println("Age:", emp.age)
    fmt.Println("City:", emp.city)
    fmt.Println("Country:", emp.country)
}

Output:


Name of employee: Joseph
Age: 54
City: italy
Country: USA

Struct Using Pointer Address Operator in Golang

A pointer to the struct data type is created with the “&” operator. All variables have memory locations and the pointer with & operator allows to access the memory location where the variable operands are allocated whereas the * operator allows accessing its corresponding values held in that location.

Example : 


package main

import "fmt"
// declaration of struct type 
type emp_details struct {
 Age  int
 Name string
 Salary int 
}

func main() {
 var emp1 = &emp_details{40, "zen", 45000} // all values are shown
 fmt.Println(emp1)

 var emp2 = &emp_details{}
 emp2.Age = 10
 emp2.Name = "Vihan"
 fmt.Println(emp2) // salary not mentioned

 }

Output:


&{40 zen 45000}
&{10 Vihan 0}

Explanation

  •    An emp_details struct type is declared.
  •   The below syntax declares variable emp1 and pointer  (&) operator used to access the memory location and its values.
    PHP : Struct
  •   Another type of initialization 
    
    var emp2 = &emp;_details{}
    emp2.Age = 10
    emp2.Name = "Vihan"
    
    
  •   A variable emp2 is declared and assigned with struct pointer type followed by accessing the fields using dot operator and initializing values for respective fields.
  •   Check the output to the above program for better understanding.