A Slice of an Array :)
Out of the box somewhere after writing your first function to return a Hello World, is an array patiently waiting to pop up next. It's a popular data structure known for being very useful with a deceitful look of being easy.
In Go, arrays are declared by specifying the number of elements and the type of the elements. Which I found annoying at first especially coming from a JS background, until I found it had an extensible layer called slice (let's circle back to this in a minute).
Declaring an Array.
var arrayName [size]elementType
var numbers [5]int
Array elements are accessible using the index. i.e
var numbers = [5]int{1, 2, 3, 4, 5}
numbers[0] = 10 // sets the first element to 10
fmt.Println(numbers[0]) // prints the first element
fmt.Println(len(numbers)) // prints the length of the array
Arrays in the context of Data Structures and Algorithms
Arrays are foundational in constructing more advanced data structures and algorithms.
Such as
1. Sorting Algorithms
Arrays are often used with sorting algorithms like QuickSort, MergeSort, and BubbleSort.
2. Searching Algorithms
Arrays are used in search algorithms like Linear Search and Binary Search. Binary Search is particularly efficient for sorted arrays,
3. Multi-dimensional Arrays
Go also supports multi-dimensional arrays, which are useful for representing matrices and performing operations on them. I.e a 3x3 matrix can be declared as:
var matrix [3][3]int
matrix[0][3] = 5 // sets the element in the first row, third column to 5
fmt.Println(matrix[0][1]) // prints the element in the first row, second column
Limitations of Array.
Aside from the fact I initially found Array in Go strange and not as soft as in JS, its fixed-size nature makes it difficult to implement flexible data structures, and that's where slices come in, which are dynamically sized.
var slice = []int{1, 2, 3, 4, 5}
slice = append(slice, 6) // appends a new element
fmt.Println(slice) // prints the slice with the new element
Understanding how to use arrays well can boost your skills in creating fast and efficient algorithms and data structures in Go.
here is a link to problems and solutions to array-based DSA questions.
See you Soonest ๐ค๐พ