One place for hosting & domains

      Understanding Arrays in Go


      Introduction

      An array in Go is an ordered sequence of elements that has its capacity defined at creation time. Once an array has allocated its size, the size can no longer be changed. Because the size of an array is static, the data structure only needs to allocate memory once, as opposed to a variable length data structure that must dynamically allocate memory so that it can become larger or smaller in the future.

      Although the fixed length of arrays can make them somewhat rigid to work with, the one-time memory allocation can increase the speed and performance of your program. Because of this, developers typically use arrays when optimizing programs. In Go, slices are the variable length version of arrays. Slices provide more flexibility and constitute what you would think of as arrays in other languages.

      In this article, you will learn how to declare an array, how to call individual elements using indexing, how to slice the array into smaller sets, and the difference between an array and a slice in Go.

      Defining an Array

      Arrays are defined by declaring the size of the array in brackets [ ], followed by the data type of the elements. An array in Go must have all its elements be the same data type. After the data type, you can declare the individual values of the array elements in curly brackets { }.

      The following is the general schema for declaring an array:

      [capacity]data_type{element_values}
      

      Note: It is important to remember that every declaration of a new array creates a distinct type. So, although [2]int and [3]int both have integer elements, their differing capacities make their data types incompatible.

      If you do not declare the values of the array’s elements, the default is zero-valued, which means that the array elements of the array will be empty. For integers, this is represented by 0, and for strings this is represented by an empty string.

      For example, the following array numbers has three integer elements that do not yet have a value:

      var numbers [3]int
      

      If you printed numbers, you would recieve the following output:

      Output

      [0 0 0]

      If you would like to assign the values of the elements when you create the array, place the values in curly brackets. An array of strings with set values looks like this:

      [4]string{"blue coral", "staghorn coral", "pillar coral", "elkhorn coral"}
      

      You can store an array in a variable and print it out:

      coral := [4]string{"blue coral", "staghorn coral", "pillar coral", "elkhorn coral"}
      fmt.Println(coral)
      

      Running a program with the preceding lines would give you the following output:

      Output

      [blue coral staghorn coral pillar coral elkhorn coral]

      Notice that there is no delineation between the elements in the array when it is printed, making it difficult to tell where one element ends and another begins. Because of this, it is sometimes helpful to use the fmt.Printf function instead, which can format strings before printing them to the screen. Provide the %q verb with this command to instruct the function to put quotation marks around the values:

      fmt.Printf("%qn", coral)
      

      This will result in the following:

      Output

      ["blue coral" "staghorn coral" "pillar coral" "elkhorn coral"]

      Now each item is quoted. The n verb instructs to the formatter to add a line return at the end.

      With a general idea of how to declare arrays and what they consist of, you can now move on to learning how to specify elements in an array with indexes.

      Indexing Arrays

      Each element in an array can be called individually through indexing. Each element corresponds to an index number, which is an int value starting from the index number 0 and counting up.

      For the coral array from the earlier example, the index breakdown looks like this:

      “blue coral”“staghorn coral”“pillar coral”“elkhorn coral”
      0123

      The first element, the string 'blue coral', starts at index 0, and the list ends at index 3 with the item 'elkhorn coral'.

      You can call a discrete element of the array by referring to its index number in brackets after the variable in which the array is stored:

      fmt.Println(coral[2])
      

      This will print the following:

      Output

      pillar coral

      The index numbers for this array range from 03, so to call any of the elements individually and assign them a value, you could refer to the index numbers like this:

      coral[0] = "blue coral"
      coral[1] = "staghorn coral"
      coral[2] = "pillar coral"
      coral[3] = "elkhorn coral"
      

      If you call the array coral with an index number greater than 3, it will be out of range, and Go will consider the action invalid:

      fmt.Println(coral[22])
      

      Output

      invalid array index 22 (out of bounds for 4-element array)

      When indexing an array, you must always use a positive number. Unlike some languages that let you index backwards with a negative number, doing that in Go will result in an error:

      fmt.Println(coral[-1])
      

      Output

      invalid array index -1 (index must be non-negative)

      Now that you know how to work with individual elements in an array, you can learn how to slice arrays to select a range of elements.

      Slicing Arrays

      By using index numbers to determine beginning and endpoints, you can call a subsection of the values within an array. This is called slicing the array. You can do this by creating a range of index numbers separated by a colon, in the form of [first_index:second_index].

      Let’s say you would like to just print the middle items of coral, without the first and last element. You can do this by creating a slice starting at index 1 and ending just before index 3:

      fmt.Println(coral[1:3])
      

      Running a program with this line would yield the following:

      Output

      [staghorn coral pillar coral]

      When creating a slice, as in [1:3], the first number is where the slice starts (inclusive), and the second number is the sum of the first number and the total number of elements you would like to retrieve:

      array[starting_index : (starting_index + length_of_slice)]
      

      In this instance, you called the second element (or index 1) as the starting point, and called two elements in total. This is how the calculation would look:

      array[1 : (1 + 2)]
      

      Which is how you arrived at this notation:

      coral[1:3]
      

      If you want to set the beginning or end of the array as a starting or end point of the slice, you can omit one of the numbers in the array[first_index:second_index] syntax. For example, if you want to print the first three items of the array coral — which would be "blue coral", "staghorn coral", and "pillar coral" — you can do so by typing:

      fmt.Println(coral[:3])
      

      This will print:

      Output

      [blue coral staghorn coral pillar coral]

      This printed the beginning of the array, stopping right before index 3.

      To include all the items at the end of an array, you would reverse the syntax:

      fmt.Println(coral[1:])
      

      This would give the following:

      Output

      [staghorn coral pillar coral elkhorn coral]

      This section discussed calling individual parts of an array by slicing out subsections. Next, you’ll learn a specific function that Go uses for arrays: len().

      Array Functions

      In Go, len() is a built-in function made to help you work with arrays. Like with strings, you can calculate the length of an array by using len() and passing in the array as a parameter.

      For example, to find how many elements are in the coral array, you would use:

      len(coral)
      

      If you print out the length for the array coral, you’ll receive the following output:

      Output

      4

      This gives the length of the array 4 in the int data type, which is correct because the array coral has four items:

      coral := [4]string{"blue coral", "staghorn coral", "pillar coral", "elkhorn coral"}
      

      If you create an array of integers with more elements, you could use the len() function on this as well:

      numbers := [13]int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}
      fmt.Println(len(numbers))
      

      This would result in the following output:

      Output

      13

      Although these example arrays have relatively few items, the len() function is especially useful when determining how many elements are in very large arrays.

      Now that you know how to use len() to output the length of arrays, you can learn how arrays differ from another common data structure: slices.

      How Arrays Differ from Slices

      As mentioned before, the primary way in which arrays are different from slices is that the size of an array cannot be modified. This means that while you can change the values of elements in an array, you can’t make the array larger or smaller after it has been defined. A slice, on the other hand, can alter its length.

      Let’s consider your coral array:

      coral := [4]string{"blue coral", "staghorn coral", "pillar coral", "elkhorn coral"}
      

      Say you want to add the item "black coral" to this array. If you try to use the append() function with the array by typing:

      coral = append(coral, "black coral")
      

      You will receive an error as your output:

      Output

      first argument to append must be slice; have [4]string

      If you create an array and decide that you need it to have a variable length, you can convert it to a slice. To convert an array to a slice, use the slicing process you learned in the Slicing Arrays step of this tutorial, except this time select the entire slice by omitting both of the index numbers that would determine the endpoints:

      coral[:]
      

      Keep in mind that you can’t convert the variable coral to a slice itself, since once a variable is defined in Go, its type can’t be changed. To work around this, you can copy the entire contents of the array into a new variable as a slice:

      coralSlice := coral[:]
      

      If you printed coralSlice, you would receive the following output:

      Output

      [blue coral staghorn coral pillar coral elkhorn coral]

      Now, try to use append() with the newly converted slice:

      newSlice := append(coralSlice, "black coral")
      fmt.Printf("%qn", newSlice)
      

      This will output the slice with the added element:

      Output

      ["blue coral" "staghorn coral" "pillar coral" "elkhorn coral" "black coral"]

      Conclusion

      In this tutorial, you learned that the array data type is a sequenced data type with a fixed length, which makes it faster for Go to process at the cost of flexibility. Arrays also can help with communication on a team of developers: When others collaborate with you on your code, your use of arrays will convey to them that you don’t intend for their lengths to be changed.

      With this data type in your tool box, you can now go more in-depth learning the variable length version of this structure: slices.



      Source link


      Leave a Comment