The Wayback Machine - https://web.archive.org/web/20240927174313/https://www.geeksforgeeks.org/arrays-in-go/
Open In App

Arrays in Go

Last Updated : 06 Sep, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Arrays in Golang or Go programming language is much similar to other programming languages. In the program, sometimes we need to store a collection of data of the same type, like a list of student marks. Such type of collection is stored in a program using an Array. An array is a fixed-length sequence that is used to store homogeneous elements in the memory. Due to their fixed length array are not much popular like Slice in Go language. In an array, you are allowed to store zero or more than zero elements in it. The elements of the array are indexed by using the [] index operator with their zero-based position, which means the index of the first element is array[0] and the index of the last element is array[len(array)-1]. 

arrays-in-golang

Creating and accessing an Array

In Go language, arrays are created in two different ways:

Using var keyword: In Go language, an array is created using the var keyword of a particular type with name, size, and elements. Syntax:

Var array_name[length]Type

Important Points:

In Go language, arrays are mutable, so that you can use array[index] syntax to the left-hand side of the assignment to set the elements of the array at the given index.

Var array_name[index] = element

  • You can access the elements of the array by using the index value or by using for loop.
  • In Go language, the array type is one-dimensional.
  • The length of the array is fixed and unchangeable.
  • You are allowed to store duplicate elements in an array.

Approach 1: Using shorthand declaration:

In Go language, arrays can also declare using shorthand declaration. It is more flexible than the above declaration. 

Syntax:

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

Example: 

Go




// Go program to illustrate how to create
// an array using shorthand declaration 
// and accessing the elements of the 
// array using for loop
package main
  
import "fmt"
  
func main() {
  
// Shorthand declaration of array
arr:= [4]string{"geek", "gfg", "Geeks1231", "GeeksforGeeks"}
  
// Accessing the elements of 
// the array Using for loop
fmt.Println("Elements of the array:")
  
for i:= 0; i < 3; i++{
fmt.Println(arr[i])
}
  
}


Output:

Elements of the array:
geek
gfg
Geeks1231

Multi-Dimensional Array

As we already know that arrays are 1-D but you are allowed to create a multi-dimensional array. Multi-Dimensional arrays are the arrays of arrays of the same type. In Go language, you can create a multi-dimensional array using the following syntax:

Array_name[Length1][Length2]..[LengthN]Type

You can create a multidimensional array using Var keyword or using shorthand declaration as shown in the below example. 

Note: In a multi-dimension array, if a cell is not initialized with some value by the user, then it will initialize with zero by the compiler automatically. There is no uninitialized concept in the Golang. 

Example: 

Go




// Go program to illustrate the
// concept of multi-dimension array
package main
  
import "fmt"
  
func main() {
  
    // Creating and initializing
    // 2-dimensional array
    // Using shorthand declaration
    // Here the (,) Comma is necessary
    arr := [3][3]string{{"C #", "C", "Python"}, {"Java", "Scala", "Perl"},
        {"C++", "Go", "HTML"}}
  
    // Accessing the values of the
    // array Using for loop
    fmt.Println("Elements of Array 1")
    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] = 100
    arr1[0][1] = 200
    arr1[1][0] = 300
    arr1[1][1] = 400
  
    // Accessing the values of the array
    fmt.Println("Elements of array 2")
    for p := 0; p < 2; p++ {
        for q := 0; q < 2; q++ {
            fmt.Println(arr1[p][q])
        }
    }
}


Output:

Elements of Array 1
C#
C
Python
Java
Scala
Perl
C++
Go
HTML
Elements of array 2
100
200
300
400

Important Observations About Array

In an array, if an array does not initialize explicitly, then the default value of this array is 0. 

Example: 

Go




// Go program to illustrate an array
package main
  
    import "fmt"
  
func main()
{
  
    // Creating an array of int type
    // which stores, two elements
    // Here, we do not initialize the
    // array so the value of the array
    // is zero
    var myarr[2] int fmt.Println("Elements of the Array: ", myarr)
}


Output:

Elements of the Array : [0 0]

In an array, you can find the length of the array using len() method as shown below: 

Example: 

Go




// Go program to illustrate how to find
// the length of the array
package main
  
import "fmt"
  
func main() {
  
// Creating array
// Using shorthand declaration    
arr1:= [3]int{9,7,6}
arr2:= [...]int{9,7,6,4,5,3,2,4}
arr3:= [3]int{9,3,5}
  
// Finding the length of the 
// array using len method
fmt.Println("Length of the array 1 is:", len(arr1))
fmt.Println("Length of the array 2 is:", len(arr2))
fmt.Println("Length of the array 3 is:", len(arr3))
}


Output:

Length of the array 1 is: 3
Length of the array 2 is: 8
Length of the array 3 is: 3

In an array, if ellipsis ‘‘…’’ become visible at the place of length, then the length of the array is determined by the initialized elements. As shown in the below example: 

Example: 

Go




// Go program to illustrate the
// concept of ellipsis in an array
package main
  
import "fmt"
  
func main() {
      
// Creating an array whose size is determined 
// by the number of elements present in it
// Using ellipsis
myarray:= [...]string{"GFG", "gfg", "geeks",
                    "GeeksforGeeks", "GEEK"}
  
fmt.Println("Elements of the array: ", myarray)
  
// Length of the array
// is determine by 
// Using len() method
fmt.Println("Length of the array is:", len(myarray))
}


Output:

Elements of the array:  [GFG gfg geeks GeeksforGeeks GEEK]
Length of the array is: 5

In an array, you are allowed to iterate over the range of the elements of the array. As shown in the below example: 

Example: 

Go




// Go program to illustrate 
// how to iterate the array
package main
  
import "fmt"
  
func main() {
      
// Creating an array whose size
// is represented by the ellipsis
myarray:= [...]int{29, 79, 49, 39,
                   20, 49, 48, 49}
  
// Iterate array using for loop
for x:=0; x < len(myarray); x++{
fmt.Printf("%d\n", myarray[x])
}
}


Output:

29
79
49
39
20
49
48
49

In Go language, an array is of value type not of reference type. So when the array is assigned to a new variable, then the changes made in the new variable do not affect the original array. As shown in the below example: Example: 

Go




// Go program to illustrate value type array
package main
  
import "fmt"
  
func main() {
      
// Creating an array whose size 
// is represented by the ellipsis
my_array:= [...]int{100, 200, 300, 400, 500}
fmt.Println("Original array(Before):", my_array)
  
// Creating a new variable 
// and initialize with my_array
new_array := my_array
  
fmt.Println("New array(before):", new_array)
  
// Change the value at index 0 to 500
new_array[0] = 500
  
fmt.Println("New array(After):", new_array)
  
fmt.Println("Original array(After):", my_array)
}


Output:

Original array(Before): [100 200 300 400 500]
New array(before): [100 200 300 400 500]
New array(After): [500 200 300 400 500]
Original array(After): [100 200 300 400 500]

In an array, if the element type of the array is comparable, then the array type is also comparable. So we can directly compare two arrays using == operator. As shown in the below example: 

Example: 

Go




// Go program to illustrate 
// how to compare two arrays
package main
  
import "fmt"
  
func main() {
  
// Arrays    
arr1:= [3]int{9,7,6}
arr2:= [...]int{9,7,6}
arr3:= [3]int{9,5,3}
  
// Comparing arrays using == operator
fmt.Println(arr1==arr2)
fmt.Println(arr2==arr3)
fmt.Println(arr1==arr3)
  
// This will give and error because the 
// type of arr1 and arr4 is a mismatch 
/*
arr4:= [4]int{9,7,6}
fmt.Println(arr1==arr4)
*/
}


Output:

true
false
false


Previous Article
Next Article

Similar Reads

How to Calculate the Average using Arrays in Golang?
Given an array of n elements, your task is to find out the average of the array.Approach: Accept the size of the array.Accept the elements of the array.Store the sum of the elements using for loop.Calculate Average = (sum/size of array)Print the average. Example: Input: n = 4 array = 1, 2, 3, 4 Output : sum = 10 average = 2.5 C/C++ Code // Golang p
2 min read
Golang
Golang is a procedural and statically typed programming language having the syntax similar to C programming language. Sometimes it is termed as Go Programming Language. It provides a rich standard library, garbage collection, and dynamic-typing capability. It was developed in 2007 by Robert Griesemer, Rob Pike, and Ken Thompson at Google but launch
2 min read
Learn Free Programming Languages
In this rapidly growing world, programming languages are also rapidly expanding, and it is very hard to determine the exact number of programming languages. Programming languages are an essential part of software development because they create a communication bridge between humans and computers. Now, if you are a beginner who wants to learn, searc
9 min read
Top 10 Golang Project Ideas with Source Code in 2024
Golang, or Go, a programming language was created by Google. It's widely used for building different kinds of applications like websites and cloud services. The fastest way to master this language is by building projects related to it. This article introduces 10 beginner-friendly to medium-difficulty projects in Golang with reference links to sourc
8 min read
Delete Elements in a Slice in Golang
A Slice in Golang is an array(list of elements of the same type) but it's dynamic i.e. it can adjust its size as per the elements added throughout the program. We can initialize a slice without specifying the initial length or size, this allows us to add elements to it dynamically. So, there might be instances, where you need to remove elements fro
7 min read
How to Sort Golang Map By Keys or Values?
Let's say we have a map and want to find a specific key-value pair but it can be located in any order, so to have the map in Golang in a particular order, we can sort the map by its keys or values. In this article, we will see how to sort a map in go lang by its keys or values.  Sort By KeysTo sort a map by keys, we need to first create a list of k
5 min read
Class and Object in Golang
Every human (excluding infants) can relate to encapsulation irrespective of his/her prior knowledge of encapsulation. Do you wonder why? Simple. Recollect all the times when you were sick, and the doctor prescribed all those monstrous capsules dosage for a couple of days until you were okay again! The evil capsule contains all mysterious elements w
6 min read
Top 5 Golang Frameworks in 2024
Golang (or Go) is an open-source compiled programming language that is used to build simple, systematic, and secure software. It was designed by Google in the year 2007 and has been readily adopted by developers all over the world due to its features like memory safety, structural typing, garbage collection, and similarity to C-language. Golang web
7 min read
How to Parse JSON in Golang?
Golang provides multiple APIs to work with JSON including to and from built-in and custom data types using the encoding/json package. To parse JSON, we use the Unmarshal() function in package encoding/json to unpack or decode the data from JSON to a struct. Syntax: func Unmarshal(data []byte, v interface{}) error Unmarshal parses the JSON-encoded d
4 min read
Inheritance in GoLang
Inheritance means inheriting the properties of the superclass into the base class and is one of the most important concepts in Object-Oriented Programming. Since Golang does not support classes, so inheritance takes place through struct embedding. We cannot directly extend structs but rather use a concept called composition where the struct is used
3 min read
Time Formatting in Golang
Golang supports time formatting and parsing via pattern-based layouts. To format time, we use the Format() method which formats a time.Time object. Syntax: func (t Time) Format(layout string) string We can either provide custom format or predefined date and timestamp format constants are also available which are shown as follows. .time-formatting-i
2 min read
fmt.Sprintf() Function in Golang With Examples
In Go language, fmt package implements formatted I/O with functions analogous to C's printf() and scanf() function. The fmt.Sprintf() function in Go language formats according to a format specifier and returns the resulting string. Moreover, this function is defined under the fmt package. Here, you need to import the "fmt" package in order to use t
2 min read
How to iterate over an Array using for loop in Golang?
An array is a data structure of the collection of items of the similar type stored in contiguous locations. For performing operations on arrays, the need arises to iterate through it. A for loop is used to iterate over data structures in programming languages. It can be used here in the following ways: Example 1: // Golang program to iterate over /
2 min read
strings.Join() Function in Golang With Examples
strings.Join() Function in Golang concatenates all the elements present in the slice of string into a single string. This function is available in the string package. Syntax: func Join(s []string, sep string) string Here, s is the string from which we can concatenate elements and sep is the separator which is placed between the elements in the fina
1 min read
strings.Contains Function in Golang with Examples
strings.Contains Function in Golang is used to check the given letters present in the given string or not. If the letter is present in the given string, then it will return true, otherwise, return false. Syntax: func Contains(str, substr string) bool Here, str is the original string and substr is the string that you want to check. Let us discuss th
2 min read
Golang program that uses switch, multiple value cases
Switch statement is a multiway branching which provides an alternative way too lengthy if-else comparisons. It selects a single block to be executed from a listing of multiple blocks on the basis of the value of an expression or state of a single variable. A switch statement using multiple value cases correspond to using more than one value in a si
3 min read
How to compare times in Golang?
With the help of Before() and After() and Equal(), function we can compare the time as well as date but we are also going to use the time.Now() and time.Now().Add() function for comparison. Functions Used: These functions compares the times as seconds. Before(temp) - This function is used to check if the given time is before the temporary time vari
2 min read
strings.Replace() Function in Golang With Examples
strings.Replace() Function in Golang is used to return a copy of the given string with the first n non-overlapping instances of old replaced by new one. Syntax: func Replace(s, old, new string, n int) string Here, s is the original or given string, old is the string that you want to replace. new is the string which replaces the old, and n is the nu
2 min read
time.Sleep() Function in Golang With Examples
In Go language, time packages supplies functionality for determining as well as viewing time. The Sleep() function in Go language is used to stop the latest go-routine for at least the stated duration d. And a negative or zero duration of sleep will cause this method to return instantly. Moreover, this function is defined under the time package. He
3 min read
Golang Tutorial - Learn Go Programming Language | Beginner to Advanced
This Golang tutorial provides you with all the insights into Go Language programming, Here we provide the basics, from how to install Golang to advanced concepts of Go programming with stable examples. So, if you are a professional and a beginner, this free Golang tutorial is the best place for your learning. Golang, or Go Programming Language, is
10 min read
How to Split a String in Golang?
In Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding. In Go strings, you are allowed to split a string into a slice with the help of the following functions. These functions are def
5 min read
How to Trim a String in Golang?
In Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding. You can trim a string in different ways using the following list of functions. All these functions are defined under strings pa
6 min read
Different ways to concatenate two strings in Golang
In Go language, the string is an immutable chain of arbitrary bytes encoded with UTF-8 encoding. In Go strings, the process of adding two or more strings into a new single string is known as concatenation. The simplest way of concatenating two or more strings in the Go language is by using + operator. It is also known as a concatenation operator. E
4 min read
Strings in Golang
In the Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where every character is represented by one or more bytes using UTF-8 Encoding. In other words, strings are the immutable chain of arbitrary bytes(including bytes with zero value) or string is a read-only slice o
7 min read
Golang Maps
In Go language, a map is a powerful, ingenious, and versatile data structure. Golang Maps is a collection of unordered pairs of key-value. It is widely used because it provides fast lookups and values that can retrieve, update or delete with the help of keys. It is a reference to a hash table.Due to its reference type it is inexpensive to pass, for
9 min read
Goroutines - Concurrency in Golang
Go language provides a special feature known as a Goroutines. A Goroutine is a function or method that executes independently and simultaneously in connection with any other Goroutines in your program. In other words, every concurrently executing activity in the Go language is known as a Goroutines. You can consider a Goroutine like a lightweight t
4 min read
Arrays in Go
Arrays in Golang or Go programming language is much similar to other programming languages. In the program, sometimes we need to store a collection of data of the same type, like a list of student marks. Such type of collection is stored in a program using an Array. An array is a fixed-length sequence that is used to store homogeneous elements in t
7 min read
Anonymous function in Go Language
Go language provides a special feature known as an anonymous function. An anonymous function is a function which doesn't contain any name. It is useful when you want to create an inline function. In Go language, an anonymous function can form a closure. An anonymous function is also known as function literal. Syntax: func(parameter_list)(return_typ
2 min read
Data Types in Go
Data types specify the type of data that a valid Go variable can hold. In Go language, the type is divided into four categories which are as follows: Basic type: Numbers, strings, and booleans come under this category.Aggregate type: Array and structs come under this category.Reference type: Pointers, slices, maps, functions, and channels come unde
7 min read
Loops in Go Language
Go language contains only a single loop that is for-loop. A for loop is a repetition control structure that allows us to write a loop that is executed a specific number of times. In Go language, this for loop can be used in the different forms and the forms are: 1. As simple for loop It is similar that we use in other programming languages like C,
5 min read