Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: Mar 27, 2024
Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

Struct is the short name for structure. A structure is defined as a user-defined type that allows to group items of different types into one single type. A structure can be used to represent any real-world entity that has properties. Structures are like classes in Object-Oriented Programming that support composition but not inheritance. Golang has the ability to declare and create structures, and it is the only way to create concrete user-defined types in Golang. Each data field in a structure is declared using a known built-in or a user-defined type. Structures improve the modularity and allow the user to create and pass complex data structures around.

Declaration

Named struct

Struct, which is short for structure, can be defined in Golang programing language to define a user-defined data type. The declaration starts with the keyword “type” followed by the name of the structure and finally the keyword “struct”. All the data fields are specified with a name and a type within curly braces.

Syntax

type structure_name struct{
// data fields
field_1 data_type
field_2 data_type
field_3 data_type
}


Example

package main

import (  
    "fmt"
)

type Student struct {  
    firstName string
    lastName  string
    age       int
}

func main() {

    //creating struct specifying field names
    std1 := Student{
        firstName: "John",
        lastName:  "Roger",
        age:       15,
    }

    fmt.Println("Student 1:", std1)
}


Output

Student 1: {John Roger 15}

Anonymous struct

In the Golang programming language, it is possible to declare structures without creating a new data type. Such types of structures are called anonymous structs.

An anonymous struct is a struct with no name. Such a struct cannot be referenced anywhere in the code.

Example

package main

import (  
    "fmt"
)

func main() {  
    std1 := struct {
        firstName string
        lastName  string
        age       int
    }{
        firstName: "John",
        lastName:  "Roger",
        age:       15,
    }

    fmt.Println("Student 1", std1)
}


Output

Student 1 {John Roger 15}
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Accessing Individual fields of a structure

Individual fields of a structure can be accessed easily in Golang using the dot “.” operator. In order to access a particular field, the syntax which is followed is name_of_structure.field_name

Example

package main

import (  
    "fmt"
)

type Student struct {  
    firstName string
    lastName  string
    age       int
    rollNo    int
}

func main() {  
    std1 := Student{
        firstName: "John",
        lastName:  "Rogers",
        age:       15,
        rollNo:    25,
    }
    fmt.Println("First Name:", std1.firstName)
    fmt.Println("Last Name:", std1.lastName)
    fmt.Println("Age:", std1.age)
    fmt.Printf("Roll No: %d\n", std1.rollNo)
    std1.rollNo = 27
    fmt.Printf("New Roll No: %d", std1.rollNo)
}


Output

First Name: John
Last Name: Rogers
Age: 15
Roll No: 25
New Roll No: 27

Zero value of a struct

In Golang, when a struct is defined and if no value is assigned to the different fields explicitly, then the fields of the struct are assigned a value zero (0) by default. In the case of strings, an empty string is assigned to that field.

Example

package main

import (  
    "fmt"
)

type Student struct {  
    firstName string
    lastName  string
    age       int
}

func main() {  
    var std1 Student 
    fmt.Println("First Name:", std1.firstName)
    fmt.Println("Last Name:", std1.lastName)
    fmt.Println("Age:", std1.age)
}


Output

First Name: 
Last Name: 
Age: 0

Ways of structure instantiation

There are 4 ways in which an instance can be created :

Using the var keyword

When declaring an instance using the var keyword, we assign values to the struct fields using the name of the structure and the dot operator.
 

Using a Struct Literal

When declaring an instance using the Struct literal, we assign the values to the fields of the struct at the time of creation.
 

Using the new keyword

When declaring an instance using the new keyword, we assign values to the struct fields using the name of the structure and the dot.

Example

package main

import "fmt"

type Student struct {
	firstName  string
	lastName string
	age   int
}

func main() {
    // using the var keyword
    var std1 Student 
	std1.firstName = "Jeremy"
	std1.lastName = "Shaw"
	std1.age = 14
	fmt.Println(std1)

    	// using the struct literal
	var std2 = Student{"John", "Roger", 15}
	fmt.Println(std2)

	std3 := new(Student)
	std3.firstName = "Captain"
	std3.lastName = "America"
	std3.age = 17
	fmt.Println(std3)

}


Output

{Jeremy Shaw 14}
{John Roger 15}
&{Captain America 17}


Using pointer address operator

When creating an instance using a pointer address, it is denoted by the & symbol.

Example

package main

import "fmt"

type Student struct {
firstName  string
lastName string
age   int
}

func main() {

    var std1 = &Student{"John", "Rogers", 15} //  we cannot skip any value
    fmt.Println(std1)
    
}


Output

&{John Rogers 15}

Nested Struct

Golang allows creating a struct type using another struct type. A structure can be nested by creating a structure type using other structure types as the type for the structure field.

Example

package main

import "fmt"

type Marks struct {
	total, cgpa float64
}

type Student struct {
	FirstName, LastName string
	Age int
	marks  Marks
}

func main() {
		std1 := Student{
			FirstName: "John",
			LastName:  "Rogers",
			Age:       15,
			marks: Marks{
			total: 458.00,
			cgpa:   8.10,
		},
	}
	fmt.Println("Full Name :",std1.FirstName, std1.LastName)
	fmt.Println("Age :",std1.Age)
	fmt.Println("Total Marks:",std1.marks.total)
	fmt.Println("CGPA:",std1.marks.cgpa)
}


Output

Full Name : John Rogers
Age : 15
Total Marks: 458
CGPA: 8.1

Add methods to structure

Golang allows the user to add methods to struct types using method receiver.

Example

package main

import "fmt"

type Marks struct {
	total, cgpa float64
}

type Student struct {
	FirstName, LastName string
	Age int
	marks  Marks
}
func (std Student) info() string {
	fmt.Println("Full Name :",std.FirstName, std.LastName)
	fmt.Println("Age :",std.Age)
	fmt.Println("Total Marks:",std.marks.total)
	fmt.Println("CGPA:",std.marks.cgpa)
	return "----------------------"
}
func main() {
	std1 := Student{
			FirstName: "John",
			LastName:  "Rogers",
			Age:       15,
			marks: Marks{
				total: 458.00,
				cgpa:   8.10,
			},
		}
	fmt.Println(std1.info())
}


Output

Full Name : John Rogers
Age : 15
Total Marks: 458
CGPA: 8.1
----------------------

FAQs

  1. Can we create a structure without declaring a new data type?
    Yes, we can create a structure without declaring a new data type, such structures are called anonymous structs.
     
  2. What is meant by zero value of a struct?
    Zero value of a struct means that If we do not explicitly assign values to different fields of a struct, then the fields of the struct are assigned a value zero by default.
     
  3. How can we access individual fields of a structure?
    The individual fields of a structure can be accessed using the dot operator. For example, if we want to access the name field of a structure whose instance is named temp, then we can access the name field by “temp.name”.

Key Takeaways

In this article, we have extensively discussed what structures are, how to declare them, the zero value of a struct, and the different ways of structure instantiation with examples in the Go programming language and their implementation in Visual Studio Code.

We hope that this blog has helped you enhance your knowledge regarding structures in the Golang programming language and if you would like to learn more, check out our articles on what golang is, what are the dynamic of Golang, what structures are in C++, and what is the difference between structures and union in C++.

Do upvote our blog to help other ninjas grow. Happy Coding!”

Topics covered
1.
Introduction
2.
Declaration
2.1.
Named struct
2.2.
Anonymous struct
3.
Accessing Individual fields of a structure
4.
Zero value of a struct
5.
Ways of structure instantiation
5.1.
Using the var keyword
5.2.
Using a Struct Literal
5.3.
Using the new keyword
5.4.
Using pointer address operator
6.
Nested Struct
7.
Add methods to structure
8.
FAQs
9.
Key Takeaways