go-learning/tour_of_go/l4/arrays.go

73 lines
1.1 KiB
Go
Raw Normal View History

2025-08-30 12:55:18 +00:00
package main
import "fmt"
func main() {
var aa [2]string
aa[0] = "Hello"
aa[1] = "World"
fmt.Println(aa[0], aa[1])
fmt.Println(aa)
primes := [6]int{2, 3, 5, 7, 11, 13}
fmt.Println(primes)
var s []int = primes[1:4]
fmt.Printf("The primes are %d and the slice is %d", primes, s)
// Slices are references to array sections
// Changing elements in a slice results in changes to the array
// So other slices referencing the same array section will also be changed
names := [4]string{
"John",
"Paul",
"George",
"Ringo",
}
fmt.Println(names)
a := names[0:2]
b := names[1:3]
fmt.Println(a, b)
// Now make some changes
b[0] = "XXX"
fmt.Println(a, b)
fmt.Println(names)
// Slice literals - like array literals, but without the length
q := []int{2, 3, 5, 7, 11, 13}
fmt.Println(q)
r := []bool{true, false, true, true, false, true}
fmt.Println(r)
sx := []struct {
i int
b bool
}{
{2, true},
{3, false},
{5, true},
{7, true},
{11, false},
{13, true},
}
fmt.Println(sx)
// Slice defaults
ss := []int{2, 3, 5, 7, 11, 13}
ss = ss[1: 4]
fmt.Println(ss)
ss = ss[:2]
fmt.Println(ss)
ss = ss[1:]
fmt.Println(ss)
}