Arrays in Golang
Arrays - Arrays in Golang or Go programming language are quite similar to other programming languages. Here are the things you need to know about arrays in Golang .
In a program, sometimes we need to store a set of data of the same type, like a list of student marks. Such a set is stored in a program using Arrays. An array is a fixed length sequence used to store identical elements in memory. Due to its fixed length, arrays are not as popular as Slices in Go language. In an array, you are allowed to store 0 or more than 0 elements in it. The elements of an array are indexed using the [] index operator with their starting position from 0 , that is, the index of the first element is array [0] and the index of the last element is array [len (array) - 1] .
Creating and accessing an Array
In Go language, arrays are created in two different ways:
Using var keyword : In Go language , array is created using var keyword of a specific type with name, size and elements. Syntax :
Var array_name[length]Type
Important Note:
In Go, arrays are mutable, so you can use the array[index] syntax on the left side of an assignment to place the elements of the array at the given index.
Var array_name[index] = element
- You can access the elements of an array using index values or by using a for loop .
- In Go language, array type is one dimensional.
- The length of the array is fixed and cannot be changed.
- You are allowed to store duplicate elements in an array.
Approach 1: Using shorthand declarations:
In Go language, arrays can also be declared using shorthand declaration. It is more flexible than the above declaration.
Syntax:
array_name:= [length]Type{item1, item2, item3,.itemN}
For example:
// Chương trình Go minh họa cách tạo //một mảng sử dụng khai báo viết tắt // và truy cập vào các yếu tố của // mảng bằng vòng lặp for package main import "fmt" func main() { // Khai báo viết tắt của mảng arr:= [4]string{"geek", "gfg", "Geeks1231", "GeeksforGeeks"} // Truy cập các phần tử của //mảng dùng vòng lặp for fmt.Println("Elements of the array:") for i:= 0; i < 3; i++{ fmt.Println(arr[i]) } }
Result:
Elements of the array: geek gfg Geeks1231
Multidimensional array
As we know, arrays are 1 dimensional but you are allowed to create multidimensional arrays in Golang . Multidimensional arrays are arrays of arrays of the same type. In Go language, you can create multidimensional arrays using the following syntax:
Array_name[Length1][Length2].[LengthN]Type
You can create a multidimensional array using the Var keyword or using a shorthand declaration as shown in the example below.
Note: In multidimensional arrays, if a cell is not initialized by the user with some value, it is automatically initialized by the compiler with zero. There is no such thing as uninitialized in Golang.
For example:
// 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]) } } // Tạo mảng 2 chiều // bằng từ khóa var // và khởi tạo // -một mảng đa chiều bằng index var arr1 [2][2]int arr1[0][0] = 100 arr1[0][1] = 200 arr1[1][0] = 300 arr1[1][1] = 400 // Truy cập các giá trị của mảng fmt.Println("Elements of array 2") for p := 0; p < 2; p++ { for q := 0; q < 2; q++ { fmt.Println(arr1[p][q]) } } }
Result:
Elements of Array 1 C# C Python Java Scala Perl C++ Go HTML Elements of array 2 100 200 300 400
Important notes about arrays in Golang:
In an array, if an array is not initialized explicitly, its default value is 0.
For example:
// Chương trình Go minh họa một mảng package main import "fmt" func main() { // Tạo một mảng kiểu int // chứa 2 thành phần // Tại đây chúng ta không khởi tạo //mảng, vì thế giá trị của mảng // bằng 0 var myarr [2]int // In mảng fmt.Println("Elements of the Array: ", myarr) }
Result:
Elements of the Array : [0 0]
In an array, you can find the length of the array using the len() method as shown below:
For example:
// Chương trình Go minh họa cách tìm // chiều dài của mảng package main import "fmt" func main() { // Tạo mảng // bằng khai báo viết tắt arr1:= [3]int{9,7,6} arr2:= [.]int{9,7,6,4,5,3,2,4} arr3:= [3]int{9,3,5} // Tìm chiều dài của // mảng bằng phương thức len 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)) }
Result
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 an ellipsis ''…'' appears in the length position , then the length of the array is determined by the initialized elements. As shown in the example below:
For example:
// Chương trình Go minh họa // khái niệm ba chấm trong một mảng package main import "fmt" func main() { // Tạo mảng có kích thước đã được xác định // bởi số phần tử nằm ở bên trong // Dùng ellipsis myarray:= [.]string{"GFG", "gfg", "geeks", "GeeksforGeeks", "GEEK"} fmt.Println("Elements of the array: ", myarray) // Chiều dài của mảng // được quyết định bởi // Dùng phương thức len() method fmt.Println("Length of the array is:", len(myarray)) }
Result:
Elements of the array: [GFG gfg geeks GeeksforGeeks GEEK] Length of the array is: 5
You should read it
- What is GoLang? How to install GoLang on Windows 10
- What is Golang? Things you need to know about Golang programming language
- Difference between Go and C++
- Functions are fields in Golang
- What is Golang? Why should you use Golang language?
- Structural equality in Golang
- How to copy one array into another array in Golang
- Anonymous structures and fields in Golang
May be interested
- Cursor and Array in C ++pointers and arrays are closely related. in fact, pointers and arrays are interchangeable in some cases.
- Anonymous structures and fields in Golanganonymous structs in golang are temporary structures with no names used for one-time purposes, while anonymous fields allow embedding of unnamed fields.
- Recommended fields in Golangin go structs, fields are encouraged to be the same as anonymous fields, the type of the field is the name of the field.
- Array data structurearray (array) is one of the oldest and most important data structures. arrays can store some fixed elements and these elements have the same type. most data structures use arrays to implement algorithms. here are the important concepts related to arrays.
- Complex String Slice in Golangthere are two terms slice and composite literal. in this article we will learn how to create a slice and use composite literal in golang.
- How to copy one slice into another slice in Golangto copy one slice into another, go provides a built-in function called copy(). this function allows you to copy elements from one slice (source slice) into another slice (destination slice).
- What is the difference between Go and Java?is golang better than java? is golang harder than java? can golang replace java? this comparison will give you the answer.
- How to create basic program in Golanghello, world! is the first basic program in any programming language. you can write this first program in golang by following the steps below.
- How to Install Go on Windowsgolang can be easily installed on windows. here is a step-by-step guide to install golang on windows.
- Recommended methods in Golangin golang structure, recommended methods work the same way as recommended fields.