TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to GO

Golang Array Examples

Create arrays with int and string elements. Iterate over an array with a for-loop.
Array. A building in downtown has 5 floors. No more can be added. This building is like an array—each floor is an element, and its size is fixed.
Types and sizes. An array is defined by its type, its size and shape. There is no universal array, but many typed and sized arrays. We build methods that act on arrays.
An example. Let us begin with a simple example that loops over an array of 3 ints. We use an array initializer to create a 3-element array. It contains the values 10, 20 and 30.

For: We use a for-loop to iterate over the array's elements. In this kind of for-loop, we specify a start, end, and an iteration.

Len: An array has a length. With len() we access the count of its elements—all elements are counted.

Len

Indexes: The array is indexed starting at 0. The last index is one less than the array's total length.

Golang program that uses array package main import "fmt" func main() { // Create an array of three ints. array := [...]int{10, 20, 30} // Loop over three ints and print them. for i := 0; i < len(array); i++ { fmt.Println(array[i]) } } Output 10 20 30
Parameters. We can pass an array (specified by both element count and type) to a method. Arrays are values. They are copied when passed to a method.

Caution: This is slow. Using slices is faster. For small arrays, passing directly may be an effective approach.

Golang program that passes array as argument package main import "fmt" func display(values [3]int) { fmt.Println(values[0]) fmt.Println(values[1]) fmt.Println(values[2]) } func main() { v := [...]int{5, 10, 15} // Pass the entire array to a method. // ... This copies the array. display(v) } Output 5 10 15
Array slice, method. Usually we pass slices of arrays to methods—this avoids a copy of the elements. Here, display() receives an int array slice.

In main: We take a full-range slice of the array. The slice contains all the elements in the four-element int array.

Golang program that uses slice of array, parameter package main import "fmt" func display(values []int) { // Loop over slice argument and display elements. for i:= 0; i < len(values); i++ { fmt.Println(values[i]) } } func main() { // Create a four-element array. array := [...]int{-1, 0, 10, 100} // Pass a slice of the array to display. // ... This slice contains all elements. display(array[:]) } Output -1 0 10 100
Array, slice benchmark. Do arrays have a performance advantage over slices? Potentially, performance information could be used to optimize many programs.

Version 1: We use an array: we assign into the array's elements, and then read from the array at indexes.

Version 2: In this version of the code, we use a slice. We perform the same actions on the slice that we use on the array.

Result: The array program has a consistent performance advantage in Go 1.8. Using an array can lead to a significant speedup.

Note: If you remove the element assignments, there is less of a difference. So an array might be faster only if you are assigning elements.

Golang program that benchmarks array, slice package main import ( "fmt" "time" ) func main() { // Create array and slice. array := [...]int{10, 20, 30} slice := []int{10, 20, 30} sum := 0 t0 := time.Now() // Version 1: assign into and read array elements. for i := 0; i < 1000000000; i++ { sum = 0 for x := 0; x < len(array); x++ { array[x] = 5 sum += array[x] } if sum == 0 { break } } t1 := time.Now() // Version 2: assign into and read slice elements. for i := 0; i < 1000000000; i++ { sum = 0 for x := 0; x < len(slice); x++ { slice[x] = 5 sum += slice[x] } if sum == 0 { break } } t2 := time.Now() // Results. fmt.Println(t1.Sub(t0)) fmt.Println(t2.Sub(t1)) } Output 1.3679763s Array: [...]int 1.6191417s Slice: []int
Arrays versus slices. In Go programs, we typically use slices. But a slice is always based on an array. We can think of arrays as the underlying storage for slices.

Quote: A slice, once initialized, is always associated with an underlying array that holds its elements (Go Specification).

A fundamental construct. Arrays are used as a building block, a foundation, of many things in languages. More complex collections can be built from arrays.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf