Train to busan, run from zombie in the train. you have 11 wagon and it is an array. Array is a data type but is have more than one values but have maximum space.
Imagine you're in a train looking for your seat suit to your ticket and then "Yiaaah" you get the it and sit on.
Yeah like the illustration, array is similar, have maximum seat and have order of seat. array order is start from 0
to hero maximum space
.
{0,1,3,4,...,100,1001}
is order of array, so if a seat that anyone person not there, the seat is still be there not disappear.
How to declare array
package main
import "fmt"
func main() {
var values [10]int
values = [10]int{0,1,2,3,4,5,6,7,8,9}
fmt.Println(values)
// Or
values2 := [10]int{0,1,2,3,4,5,6,7,8,9}
fmt.Println(values)
}
[10]int
, 10
is space maximum of array and int
is data type in the array.
but what will be happen if we assign value more than 10?
package main
import "fmt"
func main() {
values := [10]int{0,1,2,3,4,5,6,7,8,9,10}
// array index 10 out of bounds [0:10]
fmt.Println(values)
}
Yeah you get the answer.
Assign data to array
How we assign data to array? there is a simple way to do that, lets we write code below.
package main
import "fmt"
func main() {
var values [20]int
values[4] = 5
values[19] = 10
fmt.Println(values)
}
You can see in console the result is
[0 0 0 0 5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 10]
it will just store in the index, so if you want to place it in index 5, it will be there.
Multidimensional Array
Yeah train have row and column but what if we want to convert it to an array? we can write it as.
package main
import "fmt"
func main() {
seats := [4][4]string{
{"A1","A2","A3","A4"},
{"B1","B2","B3","B4"},
{"C1","C2","C3","C4"},
{"D1","D2","D3","D4"},
}
for i, item := range seats {
for j, it := range item {
fmt.Printf("[%d,%d]:%s ",i,j,it)
}
fmt.Println()
}
}
Conclusion
Now you can write array type. array is not just int but you can write it as string, bool, or array inside array.
Question: can we change value of array?
Top comments (0)