Working with arrays and slices in Go involves creating, initializing, accessing, and modifying their elements. Here's how you can work with arrays and slices in Go:
Arrays:
Declaration and initialization:
var arr [5]int // Declaration of an array with size 5 of type int
arr := [5]int{1, 2, 3, 4, 5} // Declaration and initialization of an array with size 5
Accessing and modifying elements:
fmt.Println(arr[0]) // Accessing the element at index 0
arr[1] = 10 // Modifying the element at index 1
Length of an array:
fmt.Println(len(arr)) // Prints the length of the array (5 in this case)
Slices:
Declaration and initialization:
var sl []int // Declaration of an empty slice
sl := []int{1, 2, 3, 4, 5} // Declaration and initialization of a slice
sl := arr[start:end] // Slicing an array to create a slice
Accessing and modifying elements:
fmt.Println(sl[0]) // Accessing the element at index 0
sl[1] = 10 // Modifying the element at index 1
Length and capacity of a slice:
fmt.Println(len(sl)) // Prints the length of the slice (number of elements)
fmt.Println(cap(sl)) // Prints the capacity of the slice (total available storage)
Appending elements to a slice:
sl = append(sl, 6) // Appending a single element to the slice
sl = append(sl, 7, 8, 9) // Appending multiple elements to the slice
Slicing a slice:
newSlice := sl[start:end] // Slicing a slice to create a new slice
Remember that arrays have a fixed size when declared, whereas slices are dynamically resizable. Slices are commonly used as they provide flexibility in managing collections of elements.