Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: Mar 27, 2024
Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

A fixed-length sequence used to hold homogenous items in memory is known as an array. Because of their limited length, arrays are not as popular as Slice in the Go language.

You can store either zero or more than zero entries in an array. The array's items are indexed using the [] index operator and their zero-based position; thus, the first element's index is array[0], and the last element's index is array[len(array)-1].

Arrays in Go

The array data structure in the Go programming language may store a fixed-size sequential collection of elements of the same type. A collection of data is stored in an array, although it is generally more convenient to conceive an array as a collection of variables of the same type.

Instead of defining separate variables like num0, num1,..., and num99, you define one array variable like num and use num[0], num[1],..., num[99] to represent individual variables. An index is used to access a specific element in an array.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Creating an Array

Using var keyword:

In the Go programming language, an array is constructed using the var keyword with the name, size, and members of a specific type.

Syntax

var array_name[length]data_type
or
var array_name[length]data_typle{item1, item2, item3, ...itemN}

Example

package main
import "fmt"
func main() {
	// Creating an array of int type
	// Using var keyword
	var arr [5]int
	// Elements are assigned using index
	arr[0] = 0
	arr[1] = 1
	arr[2] = 2
	arr[3] = 3
	arr[4] = 4
	// Accessing the elements of the array
	// Using index value
	fmt.Println("Elements of the Array:")
	fmt.Println("Element 1: ", arr[0])
	fmt.Println("Element 2: ", arr[1])
	fmt.Println("Element 3: ", arr[2])
	fmt.Println("Element 4: ", arr[3])
	fmt.Println("Element 5: ", arr[4])
}

Output

Elements of the Array:
Element 1:  0
Element 2:  1
Element 3:  2
Element 4:  3
Element 5:  4

Using shorthand declaration (using ‘:=’ sign):

Arrays in Go can also be declared using a shortcut declaration. It is more adaptable than the preceding declaration.

Syntax

array_name:= [length]data_type{item1, item2, item3,...itemN}

Example

// an array is created using:= sign
// accessing the elements of the
// array using for loop
package main
import "fmt"
func main() {
	// Shorthand declaration of array
	arr := [5]int{0, 1, 2, 3, 4}
	// Accessing the elements of
	// the array Using for loop
	fmt.Println("Elements of the array:")
	for i := 0; i < 5; i++ {
		fmt.Println(arr[i])
	}
}

Output:

Elements of the array:
0
1
2
3
4

Important Points on Arrays in Go

  • Arrays in Go are mutable; therefore, you may use array[index] syntax to the left of the assignment to set the array's elements to the specified index.
    var array_name[index] = element
  • You may access the array's elements by using the index value or a for loop.
  • Duplicate elements may be stored in an array.
  • The array type in Go is one-dimensional.
  • The array's length is fixed and cannot be changed.

Multi-Dimensional Array in Go

Arrays of the same kind are known as multi-dimensional arrays.

Although we already know that arrays are one-dimensional, you can design a multi-dimensional array.

Syntax

array_name[Length_arr1][Length_arr2]..[Length_arrN]data_type

In the Go programming language, if a cell in a multi-dimension array is not initialized with a value by the user, the compiler will automatically assign it to zero. 

Example

package main
import "fmt"
func main() {
	// Creating and initializing
	// 2-dimensional array
	// Using shorthand declaration
	// Here the (,) Comma is necessary
	arr := [3][3]int{{1, 2, 3},
	{4, 5, 6},
	{7, 8, 9}}
	// accessing array elements Using for loop
	fmt.Println("Elements of Array declared using := sign")
	for x := 0; x < 3; x++ {
		for y := 0; y < 3; y++ {
			fmt.Println(arr[x][y])
		}
	}
	// Creating a 2-dimensional
	// array using var keyword
	// and initializing a multi
	// -dimensional array using index
	var arr1 [2][2]int
	arr1[0][0] = 10
	arr1[0][1] = 20
	arr1[1][0] = 30
	arr1[1][1] = 40
	// Accessing the values of the array
	fmt.Println("Elements of array declared using var keyword")
	for p := 0; p < 2; p++ {
		for q := 0; q < 2; q++ {
			fmt.Println(arr1[p][q])
		}
	}
}

Output:

Elements of Array declared using := sign
1
2
3
4
5
6
7
8
9
Elements of array declared using var keyword
10
20
30
40

Difference between Array and Slice

  • Arrays have their uses, but they're a little rigid, so you don't see them in Go code very frequently. However, slices may be found anywhere. They use arrays to deliver a lot of power and ease.
  • A slice's type specification is []T, where T is the type of the slice's elements. A slice type, unlike an array type, has no set length.
  • A slice literal is declared in the same way as an array literal is, except that the element count is omitted:
    array_name:= []data_type{item1, item2, item3,...itemN}
    Or
    var array_name[]data_type
  • A slice may be created using the 'make' built-in function, which has the signature,
    func make([]T, len, cap) []T
    Where T denotes the element type of the to-be-created slice, the make function accepts a type, a length, and a capacity, which is optional. When called, make creates an array and returns a slice that references to it.
  • Slices, unlike arrays, may be extended using the built-in append method.
  • Slices are reference types, which means they are inexpensive to assign and may be given to other functions without requiring the creation of a new copy of the underlying array.

Check out this problem - First And Last Occurrences Of X

FAQs

  1. What is an array in Go?
    Instead of defining distinct variables for each value, arrays are used to store numerous values of the same type in a single variable.
     
  2. What is slice Golang?
    A slice is a variable-length sequence that holds items of the same kind.
     
  3. What is make in Go?
    Make() is a built-in slice function in Golang that is used to generate a slice.

Key Takeaways

In this article, we have extensively discussed Arrays in Go programming language. With the help of examples, we learned to create one-dimensional and two- dimensional arrays in Go.

Further, we saw some basic differences between arrays and slices in Golang.

We hope that this blog has helped you enhance your knowledge regarding Arrays in GoLang. If you would like to learn more, check out our articles on Golang ArchivesExplore many more courses from coding ninjas and build your skills. Do upvote our blog to help other ninjas grow. Happy Coding!”

Topics covered
1.
Introduction
2.
Arrays in Go
3.
Creating an Array
3.1.
Using var keyword:
3.2.
Using shorthand declaration (using ‘:=’ sign):
4.
Important Points on Arrays in Go
5.
Multi-Dimensional Array in Go
6.
Difference between Array and Slice
7.
FAQs
8.
Key Takeaways