add: arrays

This commit is contained in:
Inanc Gumus
2018-11-17 21:56:09 +03:00
parent c0dbce8062
commit a3a0d39a0b
138 changed files with 2022 additions and 1905 deletions

View File

@ -14,19 +14,89 @@ func main() {
myAge byte
herAge byte
// uncomment the code below and observe the error
// wrongDeclaration [-1]byte
// this declares an array with two byte elements
// its length : 2
// its element type: byte
ages [2]byte
zero [0]byte
ages [2]byte
// this declares an array with five string elements
// its length : 5
// its element type: string
tags [5]string
// this array doesn't occupy any memory space (its length is zero)
// its length : 0
// its element type: byte
zero [0]byte
// this array uses a constant expression
// its length : 3
// its element type: byte
agesExp [2 + 1]byte
tags [5]string
// uncomment the code below and observe the error
//
// wrongDeclaration [-1]byte
)
fmt.Printf("%d %d\n", myAge, herAge)
fmt.Printf("%#v\n", zero)
fmt.Printf("%#v\n", ages)
fmt.Printf("%#v\n", agesExp)
fmt.Printf("%#v\n", tags)
fmt.Printf("myAge : %d\n", myAge)
fmt.Printf("herAge : %d\n", herAge)
// Since arrays we've declared here don't have any elements,
// Go automatically sets all their elements to their zero values
// depending on their element type.
// #v verb prints the array's length, element type and its elements
fmt.Printf("ages : %#v\n", ages)
fmt.Printf("tags : %#v\n", tags)
fmt.Printf("zero : %#v\n", zero)
fmt.Printf("agesExp : %#v\n", agesExp)
// note:
// ages and agesExp get printed 0x0 because they're byte arrays.
// bytes are represented with hex values. 0x0 means 0.
// =========================================================================
// GETTING AND SETTING ARRAY ELEMENTS
// =========================================================================
// Note:
//
// Since, I've already declared the ages variable above,
// and, to show you the example below, I needed to create a new block.
//
// ages variable below is in a new block below. So, it's a new variable.
//
// I did so because I need to change the element type of the ages array
// to int (or, subtracting from a byte results in wraparound).
{
var ages [2]int
fmt.Println()
fmt.Printf("ages : %#v\n", ages)
fmt.Printf("ages's type : %T\n", ages)
fmt.Println("len(ages) :", len(ages))
fmt.Println("ages[0] :", ages[0])
fmt.Println("ages[1] :", ages[1])
fmt.Println("ages[len(ages)-1] :", ages[len(ages)-1])
// WRONG:
// fmt.Println("ages[-1] :", ages[-1])
// fmt.Println("ages[2] :", ages[2])
// fmt.Println("ages[len(ages)] :", ages[len(ages)])
ages[0] = 6
ages[1] -= 3
// WRONG:
// ages[0] = "Can I?"
fmt.Println("ages[0] :", ages[0])
fmt.Println("ages[1] :", ages[1])
ages[0] *= ages[1]
fmt.Println("ages[0] :", ages[0])
fmt.Println("ages[1] :", ages[1])
}
}