Arrays
- Definition: An array is a fixed-size, contiguous collection of elements of the same type.
- Characteristics:
- Size is fixed at the time of declaration and cannot be changed.
- Arrays are value types. When you assign an array to another array, it copies the entire array.
- Accessing elements is done via zero-based indexing:
arr[0]
, arr[1]
, etc.
- Example
- Initialise an empty array
- Iterate over an array to find the sum of elements inside
- Create a 2-D array
Slices
- Definition: A slice is a flexible, dynamically-sized abstraction over an array. Slices provide a way to work with subsets of arrays.
- Syntax: You can create a slice from an array or directly using a slice literal:
- Characteristics:
- Slices are reference types, meaning they reference an underlying array. When you pass a slice to a function, you’re passing a reference, not a copy of the data.
- A slice has three components: a pointer to the array, a length, and a capacity.
- You can append elements to a slice using the built-in
append
function, which may allocate a new underlying array if the capacity is exceeded.
- Example
- Create an empty string slice
- Create and initialize a string slice
- Initialize without default value (make)
- Copy by reference
- Copy by value
Maps
Maps in Go are built-in data types that associate keys with values, similar to dictionaries or hash tables in other programming languages. They are unordered collections that allow you to store and retrieve data efficiently.
- Create a map
- Create and initialize a map
- Delete a key
- Check if a key exists