A struct is a data type that groups together values of different types. Structs are useful for organizing related data into a single entity, hence making it easy to work with. This is a great use of abstracting away data.
To define a struct, you use the type
keyword followed by the name of the struct, the struct
keyword and finally, the list of fields enclosed within curly braces (This method of using type
, name and then the variable type is go's way of defining custom data types). Each field has a name and a type. For example, the following code defines a person
struct with two fields:
type person struct {
name string
age int
}
There are multiple ways of creating a variable of a particular struct type. To make one of the person
type, you can use the following ways:
p1 := person{ // p1 = person{"Rajiv", 30}
name: "Rajiv",
age: 30,
}
// Adding an '&' creates a pointer of type person
p2 := &person{ // p2 = &person{"Rajiv", 30}
name: "Rajiv",
age: 30,
}
// Make sure to pass the values in the correct order
// This avoids having to add the field name
p3 := person{"Rajiv", 30} // p3 = person{"Rajiv", 30}
This returns a pointer to the created struct.
p := new(person)
p.name = "Rajiv"
p.age = 30 // p = &person{"Rajiv", 30}
Once you have created a struct value, you can access its fields using the dot notation. For example, the following code accesses the name
field of the person
struct
fmt.Println(p.Name) // "Rajiv"
Along with accessing fields, you can also modify the values of fields using the dot notation. For example, the following code sets the age
field of the person
struct p
to 35:
p.Age = 35
fmt.Println(p.Age) // 35
One of the key advantages of using structs in Go is that they allow you to define custom data types that can be used throughout your program. This makes it easier to write modular and reusable code, as you can define a struct that encapsulates a particular set of data and then use that struct wherever you need to work with that data.
For example, the following code defines a book
struct with fields for the book's title, author, and page count:
type book struct {
title string
author string
pages int
}
This book
struct can be used to represent a book in your program. You can create a book
struct value by providing values for each of the fields, as in the following example:
bk := book{
title: "Oliver Twist",
author: "Charles Dickens",
pages: 373,
}
Once you have created a book
struct, you can access and manipulate its fields using the dot notation, as in the previous example. For instance, the following code prints the title and author of the book
struct bk
: