Understanding Arrays and Slices in Go
Arrays and slice are distinct data structures in Go. Arrays have a fixed length, while slices are dynamic arrays that can grow or shrink in size.
To create an array:
fixedArray := [5]int{10, 20, 30, 40, 50}
// Using [...] syntax for automatic length determination
autoArray := [...]int{0, 1, 2, 3, 4, 5}
To create a slice:
// Empty brackets indicate a slice
slice1 := []int{1, 2, 3, 4, 5}
// Using make with specified length and capacity
slice2 := make([]int, 6, 8)
// Omitting capacity sets it equal to length
slice3 := make([]int, 6)
Converting an array to a slice involvse extracting a segment from the array and assigning it to a new variable of slice type.
Example:
func main() {
numbers := [...]int{0, 1, 2, 3, 4, 5}
segment := numbers[2:4]
segment[0] += 100
segment[1] += 200
fmt.Println(segment)
fmt.Println(numbers)
}
// Output:
// [102 203]
// [0 1 102 203 4 5]
Common methods to array-to-slice conversion:
slice := arr[:]slice := data[2:4]slice := arr[:5]
To convert an array to a slice and expand it:
package main
import "fmt"
func main() {
originalArray := [5]int{1, 2, 3, 4, 5}
convertedSlice := originalArray[:]
additionalValue := 6
convertedSlice = append(convertedSlice, additionalValue)
fmt.Println(convertedSlice)
}
The fmt package provides formatted output functions like Printf, which uses format specifiers such as %T for type representation.
Advanced Go topics include goroutines for concurrency, channels for communication between goroutines, Go Modules for dependancy management, and ecosystem extensions like go-redis for Redis and GORM for ORM functionality.