Introduction
Arrays help you store many values of the same type together, like a row of mailboxes holding letters.
package main import "fmt" func main() { var arrayName [size]Type }
arrayName with your variable name.size with a fixed number for how many items the array holds.Type with the type of items, like int, string, etc.package main import "fmt" func main() { var emptyArray [3]int fmt.Println(emptyArray) // [0 0 0] }
package main import "fmt" func main() { var singleElementArray [1]string singleElementArray[0] = "hello" fmt.Println(singleElementArray) // [hello] }
package main import "fmt" func main() { var fruits [4]string = [4]string{"apple", "banana", "cherry", "date"} fmt.Println(fruits) }
package main import "fmt" func main() { var numbers [5]int numbers[0] = 10 numbers[4] = 50 fmt.Println(numbers) // [10 0 0 0 50] }
package main import "fmt" func main() { // Declare an array of 5 integers var dailyTemperatures [5]int // Print the array before assigning values fmt.Println("Before assigning values:", dailyTemperatures) // Assign temperatures dailyTemperatures[0] = 70 dailyTemperatures[1] = 72 dailyTemperatures[2] = 68 dailyTemperatures[3] = 65 dailyTemperatures[4] = 74 // Print the array after assigning values fmt.Println("After assigning values:", dailyTemperatures) }
var arr [3]intvar arr [3]intarr with 3 elements, each of type int.var name [size]type. So var arr [4]string is correct.package main
import "fmt"
func main() {
var nums = [3]int{10, 20, 30}
fmt.Println(nums[1])
}nums has 3 integers: 10 at index 0, 20 at index 1, and 30 at index 2.nums[1] outputs the second element, which is 20.var arr [3]int = {1, 2, 3}var arr = [3]int{1, 2, 3} or arr := [3]int{1, 2, 3}.var arr [3]int = {1, 2, 3} which misses the array type on the right side before the braces. This causes a syntax error.[2][3]int. Both dimensions must be specified.:= and correctly initializes the 2D array with two rows of three integers each.var with type on both sides (valid but less common). var matrix [][]int = {{1,2,3},{4,5,6}} is a slice of slices, not an array. var matrix [3][2]int = {{1,2},{3,4},{5,6}} has dimensions reversed (3 rows, 2 columns).Pass the test and this pattern moves unknown