Learnings Chapter: Arrays & Slices

Arrays have length and capacity

  • big difference compared to JS or Ruby
    • you declare the “capacity” of the array ie how many total elements it can hold
  • length
    • how many items currently in the array
  • capacity
    • NOTE not understanding this can lead to memory leak!
    • How many items are allocated for the array

Slice is an Array without a declared size

  • len()
    • returns length of Array
  • make()
    • creates arrays with 1arg being array type, 2nd arg array length
  • append()
    • allows you add slices together and return a new slice with a length of both arrays
    • its important because of strong typing in go

Iterating through an Array or Slice using a for loop you can use a range ex: You can see in this example we do not use the index so we use an underscore but have to use the keyword range

func Sum(numbers [5]int) int {
	sum := 0
	for _, number := range numbers {
		sum += number
	}
	return sum
}