Skip to content

Instantly share code, notes, and snippets.

@knaveightt
Created February 17, 2023 22:04
Show Gist options
  • Save knaveightt/c4d7828a0ed45c2161da45320306eb7e to your computer and use it in GitHub Desktop.
Save knaveightt/c4d7828a0ed45c2161da45320306eb7e to your computer and use it in GitHub Desktop.
Learn Go - Arrays and Slices Summary
// Arrays and Slices
package main
import (
"fmt"
)
func main() {
// basic syntax and initialization
grades := [3]int{97, 85, 93}
grades2 := [...]int{96, 84, 92} // infers size
fmt.Printf("Grades: %v\n", grades)
fmt.Printf("Grades: %v\n", grades2)
// Initialization and assignment
var students [3]string
fmt.Printf("Students: %v\n", students)
students[0] = "Lisa"
students[2] = "Arnold"
fmt.Printf("Students: %v\n", students)
fmt.Printf("Student: %v\n", students[2])
students[1] = "Ahmed"
fmt.Printf("Number of Student: %v\n", len(students))
// Matrix (array of arrays)
// var identityMatrix [3][3]int = [3][3]int{[3]int{1, 0, 0}, [3]int{0, 1, 0}, [3]int{0, 0, 1}}
var identityMatrix [3][3]int
identityMatrix[0] = [3]int{1, 0, 0}
identityMatrix[1] = [3]int{0, 1, 0}
identityMatrix[2] = [3]int{0, 0, 1}
fmt.Println(identityMatrix)
fmt.Println(identityMatrix[2][2])
// Note, assigning a variable to an array creates a copy, not pointing to the same
// you can assign the new variable the ADDRESS to have the new var point to the same values
i2 := identityMatrix
i3 := &identityMatrix
identityMatrix[2][2] = 5
fmt.Println(identityMatrix)
fmt.Println(i2)
fmt.Println(i3)
// Slice, use nothing inside of the brackets (no elipses either)
// Note, copies will automatically point to the original variable unlike arrays
slice := []int{1, 2, 3}
s2 := slice
fmt.Println(slice)
fmt.Printf("Length: %v\n", len(slice))
fmt.Printf("Capacity: %v\n", cap(slice))
fmt.Println(s2)
slice[0] = 5
fmt.Println(s2)
fmt.Println(slice)
// first number inclusive, second number exclusive
// remember, slices all point to the same data
a := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
b := a[:]
c := a[3:]
d := a[:6]
e := a[3:6]
a[5] = 42
fmt.Println(a)
fmt.Println(b)
fmt.Println(c)
fmt.Println(d)
fmt.Println(e)
// use make to make slices
f := make([]int, 3)
fmt.Println(f)
fmt.Printf("Length: %v\n", len(f))
fmt.Printf("Capacity: %v\n", cap(f))
g := make([]int, 3, 100)
fmt.Println(f)
fmt.Printf("Length: %v\n", len(g))
fmt.Printf("Capacity: %v\n", cap(g))
h := []int{}
fmt.Println(h)
fmt.Printf("Length: %v\n", len(h))
fmt.Printf("Capacity: %v\n", cap(h))
h = append(h, 1)
fmt.Printf("Length: %v\n", len(h))
fmt.Printf("Capacity: %v\n", cap(h))
fmt.Println(h)
h = append(h, 2, 3, 4, 5)
fmt.Printf("Length: %v\n", len(h))
fmt.Printf("Capacity: %v\n", cap(h))
fmt.Println(h)
// concatenate slices. ellipses spreads slice elements to individual arguments
h = append(h, a...)
fmt.Printf("Length: %v\n", len(h))
fmt.Printf("Capacity: %v\n", cap(h))
fmt.Println(h)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment