array-slice

path: courses/go-course/array-slice.md

- **fileName**: array-slice
- **Created on**: 2024-08-31 14:35:50

Arrays and Slices in Go

An array in Go is a fixed-size, ordered collection of elements of the same type. Once an array is created, its size cannot be changed. Arrays are defined with a specific length and can be initialized with values.
Syntax:

var arrayName [size]type

Example:

// Define an array of integers with 5 elements
var numbers [5]int
// Initialize the array with values
numbers = [5]int{1, 2, 3, 4, 5}
// Accessing array elements
fmt.Println(numbers[0]) // Output: 1

Slices

A slice is a more flexible and powerful abstraction over arrays. Unlike arrays, slices can grow and shrink dynamically. Slices are built on top of arrays and provide a more convenient way to work with sequences of elements.

Syntax:

var sliceName []type{values}

Example:


// Create a slice of integers
numbers := []int{1, 2, 3, 4, 5}

// Append to a slice
numbers = append(numbers, 6)

// Accessing slice elements
fmt.Println(numbers[0]) // Output: 1

// Slice a portion of a slice
subSlice := numbers[1:4] // Contains elements 2, 3, 4
fmt.Println(subSlice)    // Output: [2 3 4]
Key Differences

making slice using make Example:

// func make([]T, len, cap) []T
mySlice := make([]int, 5, 10)

In Go, when you use the make function to create a slice, you specify three parameters:

  1. Type (T): The type of elements the slice will hold (e.g., int).
  2. Length (len): The initial number of elements in the slice.
  3. Capacity (cap): The maximum number of elements the slice can grow to without reallocating.

Here's a breakdown of these concepts:

Length (len)

Capacity (cap)

for making slice adding value for it Example:

mySlice := []string{"I", "love", "go"}


when passing arguments varidadic in go can passing the slice like this

package main
import ( 
    "fmt"
    // "slices"
)
func main() {
    UserSlice := []string{"yossef", "yossef", "sabry"}
    printUser(UserSlice...)// passing slice like arguments
    //printUser("yossef", "yossef", "sabry")// passing slice like arguments
    /*
there is no difference between the two way
*/
    return
}
func printUser(values ...string) {
    for i := 0; i < len(values); i++ {
        fmt.Printf("%s ", values[i])
    }
}

now using the range keyword with slice

fruits := []string{"apple", "banana", "grape"}
for i, fruit := range fruits {
    fmt.Println(i, fruit)
}
// 0 apple
// 1 banana
// 2 grape

continue:variadic-go.md
before:interface-go.md