Arrays, slices and maps
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
package mainimport "fmt"func main() {var a [5]intfmt.Print(a)} -
Iterate over an array to find the sum of elements inside
package mainimport "fmt"func main() {var a [5]int = [5]int{1, 2, 3, 4, 5}var sum = 0for i := range a {sum += a[i]}fmt.Print(sum)} -
Create a 2-D array
package mainimport "fmt"func main() {var maze [3][3]int = [3][3]int{{1, 2, 3},{4, 5, 6},{7, 8, 9},}fmt.Print(maze)}
-
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
package mainfunc main() {var users []stringprintln(users == nil)} -
Create and initialize a string slice
package mainimport "fmt"func main() {var users []string = []string{"harkirat", "raman"}fmt.Print(users)} -
Initialize without default value (make)
package mainimport "fmt"func main() {var users []string = make([]string, 3)println(len(users))println(cap(users))fmt.Print(users[0] == "")} -
Copy by reference
package mainimport "fmt"func main() {var users []string = []string{"harkirat", "raman"}var users2 = users // Copied by referenceusers2[0] = "harkirat2"fmt.Print(users)} -
Copy by value
package mainimport "fmt"func main() {var users []string = []string{"harkirat", "raman"}var users2 = make([]string, len(users))copy(users2, users)users2[0] = "harkirat2"fmt.Print(users)}
-
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
m := make(map[string]int) // Creates a map with string keys and int values -
Create and initialize a map
m := map[string]int{"Alice": 25,"Bob": 30,} -
Delete a key
delete(m, "Alice") -
Check if a key exists
package mainimport "fmt"func main() {m := map[string]int{"Raman": 1,"kirat": 2,}delete(m, "Raman")value, exists := m["Raman"]if exists {fmt.Print("Value found ", value)} else {fmt.Print("Value not found")}}