In this tutorial, we will learn about master Golang struct data structure using 4 easy examples. Like any other programming language, Golang also supports many built-in and composite data structures. Struct is very powerful and user friendly data structure that allows the developers to group together different types of data fields under the same data structure. We will learn about all important aspects of Struct in the upcoming sections of this tutorial. So, let us get started.
What is Struct in Golang?
In Golang, there are two types of data structures, built-in types and composite types. Struct is one of the composite type data structure which groups together zero or more value with different data types under a single name. Each value in a struct is called a field. We can access these field using the dot notation. We use struct to model real world entities by grouping related data together. This makes it easier to manipulate and manage data in Go programs.
To define a struct in Golang, we use the keyword ‘type’ followed by the struct name and the list of fields with their respective data types. For example, we have defined a struct which holds three fields (you can define any number of fields) as shown below.
type Job struct { medical string engineer string jobId int }
After defining the struct, we initialize all the fields by creating an instance of the struct using below manner. Here each field has been assigned with a value of its type.
job := Job{ medical: "Doctor", engineer: "Software Developer", jobId: 143, }
Once the struct instance is created and all the fields are initialized, we can now access the fields using dot operator as shown below.
job.medical job.engineer job.jobId
Master Golang Struct Data Structure [4 Easy Examples]
So far so good. We talked about basics of struct that is its creation, initialization and fields accessibility. Next, we will write some code and understand more advance operations of struct such as different ways to create struct, how to add fields in existing struct, and how to access the fields of a struct. Let us look at each of these operations one by one.
Also Read: [Solved] Golang Brain Storming Interview Coding Question with Solution
How to Create Golang Struct Data Structure
In Golang, There are two ways to create “struct” data structure. First way is by using “var” keyword. Second way to create the struct is by using the “dot” (:=) notation. Let us look at each of these ways to create struct one by one using examples for better understanding.
NOTE:
Example-1: Create using var keyword
Let us understand the implementation using below example, We have created a struct called “EmpDetail”. This struct holds three fields, name, id and job of Employees. In the main function, we have created an object of EmpDetail struct called “ep2” using “var” keyword. Next, we have initialized the values of struct fields name, id and job. At the end, we print the Employee detail using fmt.Println built-in function. Save below example code in a new file and execute to see what output it returns.
package main import "fmt" type EmpDetail struct { name string id int job string } func main() { var ep2 EmpDetail ep2 = EmpDetail{"Alexander", 32, "Software Engineer"} fmt.Println("Created Struct data structure using 'var' keyword: ", ep2) }
Created Struct data structure using 'var' keyword: {Alexander 32 Software Engineer}
The above code execution will return the detail of an employee which is created during the instantiation of given struct.
Example-2: Create using Dot Notation
We will understand the struct creation using dot notation with below example. We have create a struct in a similar manner which we used in previous example. The difference is in the main function where we have instantiated the struct data structure to “EmpDetail”. We have instantiated and stored it in a variable called. “ep” using := operator. Save the below example code and execute the code to see the output it returns.
package main import "fmt" type EmpDetail struct { name string id int job string } func main() { ep := EmpDetail{"Ricky", 40, "Solution Architect"} fmt.Println("Created Struct data structure using 'dot' notation: ", ep) }
Created Struct data structure using 'dot' notation: {Ricky 40 Solution Architect}
The above output will again return the employee details which was passed to the struct object during the instantiation.
How to Modify Struct Fields ?
Also Read: Understand Functions in Golang: [7 Best Examples]
In Golang, it is possible to modify the value of an existing struct object. To do this job, we have to first create an object of struct like we did before. Next, we will store the struct object address in a variable called “epAddress”. Next, we will select the field which we want to modify using dot operator. For example, we are modifying the value of field “job”. We have assigned a new value to it as “CEO”. Save the below example code and see the output it returns. You will notice that the Employee detail after modifying the struct field will change to new value.
Example-3: Modify existing Struct Field Values
package main import "fmt" type EmpDetail struct { name string id int job string } func main() { ep := EmpDetail{"Adam", 42, "Solution Architect"} fmt.Println("Employee Data Before Promotion: ", ep) //store ep object's address epAddress := &ep epAddress.job = "CEO" fmt.Println("Employee Data After Promotion: ", ep) }
Employee Data Before Promotion: {Adam 42 Solution Architect} Employee Data After Promotion: {Adam 42 CEO}
How to Add Field in Existing Struct
In Golang, it is possible to add new fields to an existing struct. This can be achieved in many ways. The most common way which we also will use is by creating a new struct and define the existing struct as one of the field in the new struct as shown in below example. We have create a new struct called “newEmpFields”.
It holds three fields, EmpDetail (which is an existing struct), hobby and salary. This new struct will add hobby and salary field to the existing struct so that each object will return all these fields when executed. When we create the object of struct during the instantiation in main function, we pass all the fields values to the object in a slightly different manner. Save the below example file and see how the field addition works.
Example-4: Add new Fields to Existing Struct
package main import "fmt" type EmpDetail struct { name string id int job string } type newEmpFields struct { EmpDetail hobby string salary int } func main() { ep := newEmpFields{EmpDetail{"Adam", 42, "Solution Architect"}, "Sports", 50000} fmt.Println("Employee Data Before Promotion: ", ep) //store ep object's address epAddress := &ep epAddress.job = "CEO" epAddress.salary = 90000 fmt.Println("Employee Data After Promotion: ", ep) }
Employee Data Before Promotion: {{Adam 42 Solution Architect} Sports 50000} Employee Data After Promotion: {{Adam 42 CEO} Sports 90000}
Summary
Reference go.dev.