Broad Network


Arrays and Slices Explanation for app.codility.com/programmers in Go

Category of Article : Technology | Computers and Software | Algorithm

By: Chrysanthus Date Published: 2 May 2025

An array is a list structure that can be used to store many items in one place. In Go, the items have to be of the same type. Imagine that there is a list of items; for example, a shopping list. The items are listed in one column or in one row on a paper. Such a column or row is conceptually similar to an array. Similarly, if air temperatures for each day in a locality, are planned to be recorded over the next 365 days, then all the temperatures would be recorded in one array. The array will have 365 data entries.

Creating an Array

One way to create an array is as shown in the following program:

    var fruits = [3]string{"bread", "butter", "cheese"};

It begins with the reserved word, var. This is followed by a space and then the name of the array. That is followed by a space and then the assignment operator (=). That is followed by a space. The right hand side of the statement begins with square brackets. Inside the square brackets, the number of elements in the array is typed. Typing this number is optional. In this statement, the data type is a string, which is typed just after the square brackets. The different string data are each typed within double quotes, separated by commas. The last element does not have a comma.

If the programmer does not want to use the the reserved word, var, then the special assignment operator, := has to be used, as follows:

    fruits := [3]string{"bread", "butter", "cheese"};

The 3 is still optional here.

An array can still be declared without elements. The way to do this is illustrated in:

        var fruits [3]string;

Here, the number in the square brackets is not optional. This array has the default values, which is "" for strings and 0 for ints.

In theory, this created array is empty.

Giving an Array, Elements

When an array is created with the initializer_list, the elements (values) are already given. If the array is created with just a simple declaration and not effectively defined, then the array values have to be given, for the different elements, as follows:

        var fruits [3]string;
        
        fruits[0] = "bread";
        fruits[1] = "butter";
        fruits[2] = "cheese";

An array can be seen as different variables next to one another, but with the same name. The actual different variables are differentiated by indexes. Index counting begins from 0, and not 1. The index for a particular value is in square brackets, just after the array name.

Accessing Array Values

Array values in Go can be read one-by-one. This is done using the subscript notation (index in square brackets). The syntax is:

   var newVariableName type = arrayName[index]; 
   
OR

   newVariableName := arrayName[index]; 

The following code segment will output "butter" after the array has been created:

        var vr = fruits[1];
        fmt.Println(vr);

The fmt.Println(vr) statement sends the value of var to the terminal (screen) and then sends the cursor (I-bar, flashing) to the next line below, at the output.

It has been explained above, how to set (give) value to an array element.

Modifying an Array

The elements of a Go array can only be modified, one-by-one. The subscript notation is still used. The syntax is:

    arrayName[index] = value;

The value has to be of the same type as all the array elements. The following code segment will output "chocolate paste" instead of "cheese", after the above array has been created:

        fruits[2] = "chocolate paste";
        fmt.Println(fruits[2]);

The index corresponding to the array value "cheese" is 2. "cheese" was replaced by "chocolate paste".

In Go, once an array has been created, its length cannot be changed. This means that a new item cannot be added after the last item of the array.

The length of an array can also not be reduced, once created.

The length of an array is determined as in the following example:

    len(arr)    //function call
    
where len is a reserved word for length and arr is the array name.

Iterating over an Array

The for-Loop

The while-loop has a difference with the do-while-loop. The for-loop is another way of coding the while-loop. The above while-loop code segment would be coded with the for-loop as follows:

    package main
    import ("fmt")
    
    func main() {
        var arr = [3]string{"bread", "butter", "cheese"};
        
        for i := 0; i<3; i += 1 {
            fmt.Println(arr[i]);
        }
    }

The for-loop begins with the reserved word, "for" with all letters in lowercase. Then there are three statements, with the last one not ending with a semicolon. The last statement is the increment statement. The middle statement is the while-condition. The first statement is the initialization of i to 0. The body (curly brackets) has one or more statements to be executed repeatedly.

Slice

A Go array has the following limitations:

A slice means a copy of a sequence of elements from an array. However, in Go, a slice can be created as a stand alone data structure, which overcomes the limits of the array.

This section, only shows how to create a slice, how to determine the current size of the slice, and how to add elements at the back of the slice.

Creating a Slice

A Slice of the above three strings can be created as in the following program:

    package main
    import ("fmt")
    
    func main() {
        myslice := []string{"bread", "butter", "cheese"};
                        
        for i := 0; i<3; i++ {
            fmt.Println(myslice[i]);
        }
    }

The statement that creates the slice is:

    myslice := []string{"bread", "butter", "cheese"};

No number goes into the square brackets. The output is the three strings. An empty slice of strings would be created as follows:

    myslice := []string{};

Size of the Slice

The following expression would return the length or size of the Slice:

    len(myslice)

where len() is a function.

The append() Function

Append means add at the end. append() is another Go function. Its first argument is the name of the slice and the rest of its arguments are elements to be added. The following program illustrates its use:

    package main
    import ("fmt")
    
    func main() {
        myslice := []string{};
        myslice = append(myslice, "bread");
        myslice = append(myslice, "butter");
        myslice = append(myslice, "cheese");
                        
        for i := 0; i < len(myslice); i ++ {
            fmt.Println(myslice[i]);
        }
    }

The output is the three elements as before. The append() function in Go returns a new slice that contains the original elements plus the appended element. It does not modify the original slice in place, because the the underlying array might need to be reallocated in memory.

Conclusion

An array can be created as the following two code segments show:

        var fruits = [3]string{"bread", "butter", "cheese"};

        var fruits [3]string;
        fruits[0] = "bread";
        fruits[1] = "butter";
        fruits[2] = "cheese";

A slice can be created as the following two code segments show:

    myslice := []string{"bread", "butter", "cheese"};
    
    myslice := []string{};
    myslice = append(myslice, "bread");
    myslice = append(myslice, "butter");
    myslice = append(myslice, "cheese");

Both the array and the ArrayList can be handled with subscripts (index in square brackets).

The rest of the 17 lessons, with explanation of lessons, explanation of tasks, and explanation of solutions, can be found at (click): Explanations in Go for the 17 Algorithm Lessons at https://app.codility.com/programmers with Problems and Solutions





Related Links

More Related Links

Cousins

NEXT

Comments