Table of Contents
Comparing Arrays and Structs in GO
- Go uses both arrays and structs to store and organize data, with some important differences.
- An array is a collection of elements of the same type stored in contiguous locations. The array length is fixed and cannot be changed. Array elements are accessed by index, and arrays can be iterated using a for loop or the range keyword.
- A struct, on the other hand, are a collection of fields, each with its own type. Structures can have different types of fields, with varying numbers of fields. Structure fields are accessed using dot notation. A struct can also have methods, which are functions associated with the struct.
- Comparing arrays and structs in Go, the main difference is that arrays are fixed length and cannot be resized, whereas structs can have a variable number of fields.
- Another difference is that arrays can only contain elements of the same type, whereas structs can contain fields of different types. In terms of memory usage, arrays are more efficient because they are stored in contiguous blocks of memory, whereas structs require additional memory to store field names.
- The choice between using arrays or structs in Go depends on your specific use case. Arrays are good when you need to store a fixed number of elements of the same type. A struct is better if you need to store a collection of fields of different types.
How to declare and use an Array in GO
In this example, an array of integers is declared with a fixed length of 3. Then values are assigned to the elements of the array and finally the array is printed.
package main
import "fmt"
func main() {
// Declare an array of integers with a fixed length of 3
var myArray [3]int
// Assign values to the elements of the array
myArray[0] = 1
myArray[1] = 2
myArray[2] = 3
// Print the array
fmt.Println(myArray) // [1 2 3]
}
How to declare and use struct in GO?
In this example, a struct of type Person
is declared with two fields: name
and age
. Then values are assigned to the fields of the struct and finally the struct is printed.
package main
import "fmt"
type Person struct {
name string
age int
}
func main() {
// Declare a variable of type Person
var myPerson Person
// Assign values to the fields of the struct
myPerson.name = "Amit"
myPerson.age = 30
// Print the struct
fmt.Println(myPerson) // {Amit 30}
}
How to create and initialize Array of Structs in GO?
Example-1: Initialize array of structs
In this example, an array of structs of type Person
is declared. The struct has two fields, name
and age
. Then, values are assigned to the elements of the array, in this case, three people. Finally, the array is printed.
package main
import "fmt"
type Person struct {
name string
age int
}
func main() {
// Declare an array of type Person
var people [3]Person
// Assign values to the elements of the array
people[0] = Person{name: "Amit", age: 30}
people[1] = Person{name: "Rahul", age: 25}
people[2] = Person{name: "Ravi", age: 35}
// Print the array
fmt.Println(people) // [{Amit 30} {Rahul 25} {Ravi 35}]
}
Example-2: Use composite literal to initialize the array of structs
We can also use composite literal to initialize the array of structs:
package main
import "fmt"
type Engineers struct {
name string
age int
}
func main() {
// Declare an array of type Engineers
members := [3]Engineers{
{"Amit", 30},
{"Rahul", 25},
{"Ravi", 35},
}
// Print the array
fmt.Println(members) // [{Amit 30} {Rahul 25} {Ravi 35}]
}
We can access the individual elements of the array by their index and access the fields of the struct using the dot notation.
fmt.Println(members[1].name) // Rahul
fmt.Println(members[1].age) // 25
You can also iterate over the array of structs using a for
loop or the range
keyword.
for i, person := range members {
fmt.Printf("Person %d: %s\n", i, person.name)
}
Output:
Person 0: Amit
Person 1: Rahul
Person 2: Ravi
Example-3: Using a pointer to an array of structs
We can use a pointer to an array of structs, which allows the structs to be modified through the pointer:
package main
import "fmt"
type Engineers struct {
name string
age int
}
func updateAge(people *[3]Engineers, index int, age int) {
people[index].age = age
}
func main() {
people := [3]Engineers{
{"Amit", 30},
{"Rahul", 25},
{"Ravi", 35},
}
updateAge(&people, 1, 27)
fmt.Println(people) // [{Amit 30} {Rahul 27} {Ravi 35}]
}
The updateAge
function is defined to take a pointer to an array of structs of type Engineers
as its first argument. The pointer is denoted by the *
symbol before the array type. By passing a pointer to the array, the function is able to modify the original array and not just a copy of it.
The index
argument is the index of the struct in the array that you want to update, and the age
argument is the new age you want to set for that struct.
The &
operator is used to pass the address of the array to the function, allowing the function to modify the original array.
Example-4: Using slice of structs
Slice is a dynamic, resizable version of an array. Unlike arrays, slices do not have a fixed length and can be resized using the append
function. Slices are often used instead of arrays in Go programs, because they provide more flexibility and convenience when working with collections of data.
package main
import "fmt"
type Person struct {
name string
age int
}
func main() {
// Declare a slice of type Person
people := []Person{
{"Amit", 30},
{"Rahul", 25},
{"Ravi", 35},
}
// Append a new element to the slice
people = append(people, Person{"Emily", 22})
// Print the slice
fmt.Println(people) // [{Amit 30} {Rahul 25} {Ravi 35} {Emily 22}]
}
In this example, a segment of a struct of type Person
is declared and initialized with three members. New elements are then added to the slice using the append
function. The append function takes two arguments.
- original disc
- the item you want to add
It then returns a new slice with the added elements. The original slice is modified by reassigning it to the returned slice.
You can also use the make
function to create a slice of structs with a specific length and capacity:
people := make([]Person, 0, 3)
This example uses the make
function to create an empty structure slice of length 0 and capacity 3. This means that the slice can contain up to 3 elements, but is currently empty.
You can access individual elements of the slice by index and fields of the structure using dot notation. You can iterate over a slice using a for
loop or the range
keyword.
Slices also have built-in methods such as len
and cap
to get the length and capacity of the slice respectively.
Slices are more convenient than arrays when working with collections of data because they are dynamic and resizable. This means that you can add or remove elements from the slice without manually resizing the underlying array.
Summary
- An array is a collection of elements of the same type stored in contiguous locations. The array length is fixed and cannot be changed.
- A struct is a collection of fields, each with its own type. Structures can have different types of fields, with varying numbers of fields.
- Comparing arrays and structs in Go, the main difference is that arrays are fixed length and cannot be resized, whereas structs can have a variable number of fields. Another difference is that arrays can only contain elements of the same type, whereas structs can contain fields of different types.
- In terms of memory usage, arrays are more efficient because they are stored in contiguous blocks of memory, whereas structs require additional memory to store field names.
- Arrays are useful when you need to store a fixed number of elements of the same type. Structures are good when you need to store a collection of fields of different types.
- In Go, you can use arrays of structs to organize collections of structs. You can either initialize an array of structs with a composite literal, or create an array with null values and fill it with structs.
- Slices are a dynamic, resizable version of arrays that are often used in Go programs because they provide greater flexibility and convenience when working with collections of data.
- You can also use a pointer to an array of structures. This allows you to modify the original array, not just a copy of the array.
- You can also use a map of structures. This allows fast and efficient searches using keys.