A structure or struct in Golang is a user-defined type that allows to group/combine items of possibly different types into a single type. Any real-world entity which has some set of properties/fields can be represented as a struct. This concept is generally compared with the classes in object-oriented programming. It can be termed as a lightweight class that does not support inheritance but supports composition. For Example, an address has a name, street, city, state, Pincode. It makes sense to group these three properties into a single structure address as shown below.
Declaring a structure:
type Address struct {
name string
street string
city string
state string
Pincode int
}
In the above, the type keyword introduces a new type. It is followed by the name of the type (Address) and the keyword struct to illustrate that we’re defining a struct. The struct contains a list of various fields inside the curly braces. Each field has a name and a type.
Note: We can also make them compact by combining the various fields of the same type as shown in the below example:
type Address struct {
name, street, city, state string
Pincode int
}
To Define a structure: The syntax for declaring a structure:
var a Address
The above code creates a variable of a type Address which is by default set to zero. For a struct, zero means all the fields are set to their corresponding zero value. So the fields name, street, city, state are set to “”, and Pincode is set to 0. You can also initialize a variable of a struct type using a struct literal as shown below:
var a = Address{"Akshay", "PremNagar", "Dehradun", "Uttarakhand", 252636}
Note:
- Always pass the field values in the same order in which they are declared in the struct. Also, you can’t initialize only a subset of fields with the above syntax.
- Go also supports the name: value syntax for initializing a struct (the order of fields is irrelevant when using this syntax). And this allows you to initialize only a subset of fields. All the uninitialized fields are set to their corresponding zero value. Example:
var a = Address{Name:”Akshay”, street:”PremNagar”, state:”Uttarakhand”, Pincode:252636} //city:””
Go
package main
import "fmt"
type Address struct {
Name string
city string
Pincode int
}
func main() {
var a Address
fmt.Println(a)
a1 := Address{"Akshay", "Dehradun", 3623572 }
fmt.Println("Address1: ", a1)
a2 := Address{Name: "Anikaa", city: "Ballia",
Pincode: 277001 }
fmt.Println("Address2: ", a2)
a3 := Address{Name: "Delhi"}
fmt.Println("Address3: ", a3)
}
|
Output:
{ 0}
Address1: {Akshay Dehradun 3623572}
Address2: {Anikaa Ballia 277001}
Address3: {Delhi 0}
How to access fields of a struct?
To access individual fields of a struct you have to use dot (.) operator.
Example:
Go
package main
import "fmt"
type Car struct {
Name, Model, Color string
WeightInKg float64
}
func main() {
c := Car{Name: "Ferrari", Model: "GTC4",
Color: "Red", WeightInKg: 1920 }
fmt.Println("Car Name: ", c.Name)
fmt.Println("Car Color: ", c.Color)
c.Color = "Black"
fmt.Println("Car: ", c)
}
|
Output:
Car Name: Ferrari
Car Color: Red
Car: {Ferrari GTC4 Black 1920}
Pointers to a struct
Pointers in Go programming language or Golang is a variable which is used to store the memory address of another variable. You can also create a pointer to a struct as shown in the below example:
Go
package main
import "fmt"
type Employee struct {
firstName, lastName string
age, salary int
}
func main() {
emp8 := &Employee{"Sam", "Anderson", 55 , 6000 }
fmt.Println("First Name:", (*emp8).firstName)
fmt.Println("Age:", (*emp8).age)
}
|
Output:
First Name: Sam
Age: 55
The Golang gives us the option to use emp8.firstName instead of the explicit dereference (*emp8).firstName to access the firstName field. Example to show this is following:
Go
package main
import "fmt"
type Employee struct {
firstName, lastName string
age, salary int
}
func main() {
emp8 := &Employee{"Sam", "Anderson", 55 , 6000 }
fmt.Println("First Name: ", emp8.firstName)
fmt.Println("Age: ", emp8.age)
}
|
Output:
First Name: Sam
Age: 55
In Go, a structure is a composite data type that groups together zero or more values of different types. Structures are defined using the type keyword, followed by the name of the new type, and the keyword struct. Here’s an example:
In this example, we define a new type Person that has three fields: Name of type string, Age of type int, and Address of type string. We can then create new instances of the Person type and set the values of its fields:
Go
func main() {
person := Person{
Name: "John Doe" ,
Age: 30 ,
Address: "123 Main St" ,
}
fmt.Println(person)
}
|
- Output:
{John Doe 30 123 Main St}
Advantages of using structures in Go:
- Encapsulation: Structures allow you to encapsulate related data together, making it easier to manage and modify the data.
- Code organization: Structures help to organize code in a logical way, which makes it easier to read and maintain.
- Flexibility: Structures allow you to define custom types with their own behavior, making it easier to work with complex data.
- Type safety: Structures provide type safety by allowing you to define the type of each field, which helps to prevent errors caused by assigning the wrong type of value.
- Efficiency: Structures in Go are very efficient, both in terms of memory usage and performance.
Disadvantages of using structures in Go:
- Complexity: Structures can make code more complex, especially if the structures have a large number of fields or methods.
- Boilerplate code: When defining large structures with many fields, it can be time-consuming to write out all of the field names and types.
- Inheritance: Go does not support inheritance, which can make it more difficult to work with large hierarchies of related data.
- Immutability: Go structures are mutable by default, which can make it more difficult to enforce immutability in your code.
- Overall, the advantages of using structures in Go typically outweigh the disadvantages, as they provide a powerful tool for managing and working with complex data. However, as with any programming technique, it’s important to use structures judiciously and be aware of their limitations.
Here are some important points about structures in Go:
- Structures are composite data types that allow you to group together related data of different types.
- In Go, structures are defined using the type keyword, followed by the name of the new type, and the keyword struct.
- Structures can have fields that are of any type, including other structures.
- Fields can be accessed using the dot . operator.
- Structures in Go can also have methods associated with them.
- Methods can be defined on structures using the receiver syntax.
- Structures can be used to create custom types that encapsulate related data and behavior.
- Go structures are mutable by default, but you can create immutable structures by using pointers or methods that return a new instance of the structure.
- Structures in Go are very efficient in terms of both memory usage and performance.
- Go does not support inheritance, but you can use composition to achieve similar results.
Overall, structures in Go are a powerful tool for managing and working with complex data. By grouping related data together and associating behavior with it, you can create custom types that are more expressive and easier to work with.