forked from steger/pr3-sose2026
50 lines
1.1 KiB
Go
50 lines
1.1 KiB
Go
package main
|
|
|
|
import "fmt"
|
|
|
|
func main() {
|
|
|
|
// Arrays in Go have a fixed size and a specific type.
|
|
var a [5]int
|
|
fmt.Println("emp:", a)
|
|
|
|
// Set and get a value.
|
|
a[4] = 100
|
|
fmt.Println("set:", a)
|
|
fmt.Println("get:", a[4])
|
|
|
|
// The builtin len returns the length of an array.
|
|
fmt.Println("len:", len(a))
|
|
|
|
// Array literals
|
|
b := [5]int{1, 2, 3, 4, 5}
|
|
fmt.Println("dcl:", b)
|
|
|
|
// An array literal with [...] can be used to let the compiler count the array elements.
|
|
b = [...]int{1, 2, 3, 4, 5}
|
|
fmt.Println("dcl:", b)
|
|
|
|
// Array literals with an index can initialize the specified values and any unspecified
|
|
// values will be set to the zero value of the array's element type.
|
|
b = [...]int{100, 3: 400, 500}
|
|
fmt.Println("idx:", b)
|
|
|
|
// Multidimensional arrays
|
|
var twoD [2][3]int
|
|
for i := 0; i < 2; i++ {
|
|
for j := 0; j < 3; j++ {
|
|
twoD[i][j] = i + j
|
|
}
|
|
}
|
|
fmt.Println("2d: ", twoD)
|
|
|
|
// Array literals for multidimensional arrays
|
|
twoD = [2][3]int{
|
|
{1, 2, 3},
|
|
{1, 2, 3},
|
|
// The comma is required here, even though it's the last element.
|
|
// This helps make diffs cleaner when new elements are added.
|
|
}
|
|
fmt.Println("2d: ", twoD)
|
|
}
|