ARRAYS IN GO

ARRAYS IN GO

·

2 min read

*what are arrays in Go?

An array is a data structure that contains a group of elements, these elements are all of the same data type, such as an integer, string or boolean. In GO the length of an array can't be modified , by this i mean it can't grow or shrink. So let us dive into the code

I will be using vscode throughout this article you can pretty much use any code editor of your choice

So we will create a folder and in the folder we will create a file named

Main.go

Screenshot from 2020-09-15 15-26-11.png Like so

next thing to do is to import the main package and define our main function

package main

func main(){

}

so there are 2 ways to go when creating an array .

I will take us through both so to create an array we specify , the name of the array, the data type, the length

  • so the first style is to set the values straight when creating it or

  • set the values later

So we start with the first method

we will create an array with 5 numbers and give it a name of a

var a [5]int

so to put values in this we can simply do

  fmt.Println("values:", a)

we should come out of the debug console with an empty value ...this is because we haven't assigned any number or value to the 5 integers space available to do that we can go by

a[0] = 1
 a[1] = 50
  a[2] = 100
 a[3] = 150
a[4] = 200

index of arrays always start with 0

now we can print it by saying

    fmt.Println("values of a:", a)

when we run it something like this should come up

Screenshot from 2020-09-15 16-14-19.png

we can also just get specific values of each index like

fmt.Println("values of 5th number is", a[4])

we should have 200 as our value printed

we can also get the length of the array like this

    fmt.Println("length of the array is",len(a))

when we run this we should get 5 as the answer

so the other method of creating an array is giving it value from the creation

like

    b := [6]int{2, 3, 5, 7, 11, 13}

if we print the values we will get the listed values

THANK YOU FOR READING