Structure of Slices in Golang

We use arrays for including same types of variables and if you want to define an array of numbers( such as shopping list) and we do that in Go like that:

array := [4]string{“shirt”, “shoes”, “watch”, “jacket”}

package arrays

import “fmt”

func Demo1() {

array := [4]string{“shirt”, “shoes”, “watch”, “jacket”}

fmt.Println(“Shop Array:”, array)
}

And it’s output is Shop Array: [shirt shoes watch jacket]

We can use arrays in with many ways but they are not so agile, if we want to edit that shopping array few days later. We should change numbers amount of array firstly and than we should add the new material to our code. And we use slices for using agile arrays.
For having slices in our code we can define that like:

“My component name is ‘that’ and make it for string about 4 variables” and that request equals to array := make([]string, 4). That is empty now but when we want to run our code, we wont have error.

array := make([]string, 4)

fmt.Println(array, len(array))

And it’s output is :

Seems like it is empty but that output has 4 pieces space value.
We said “adding new value is easy with slices”, so how to do that?
If try to do that with tradional way, our code will be like that and we will have error like that:

array := make([]string, 4)
fmt.Println(array, len(array))

array[0] = “shirt”
array[1] = “shoes”
array[2] = “watch”
array[3] = “jacket”
array[4] = “trousers”

fmt.Println(array)

So we should do this with “append” method, after using that method we will ask length of this slice. Output will be firstly 4 and lately 5:

array := make([]string, 4)
fmt.Println(array, len(array))

array[0] = “shirt”
array[1] = “shoes”
array[2] = “watch”
array[3] = “jacket”
array = append(array, “trousers”)
fmt.Println(array)
fmt.Println(len(array))

Now if we want to use more of agility of slices we can use copy method also. In example if that shopping list (shirt, shoes, watch, jacket, trousers) belongs to A company but we have got more materials from B Company. We can copy values from A company and we will add the other materials to second list.

For that we will create arrayB and we will copy values from array variable. At the final step we will add our different values.

arrayB := make([]string, len(array))
copy(arrayB, array)

arrayB = append(arrayB, “necklace”, “bag”)

Code and output will be like that at the final.

curious about cloud & automation