Zum Hauptinhalt springen
Intelligence View
⚡ tsecurity.de Intelligence

Array in Go

What is an Array in Go? In Go, an array is a fixed-size, ordered set of values with the same type. Imagine an array as a 12 egg tray; the minimum number of…

Beitrag
0
Seite
0
↗ Quelle (dev.to)
Quelle & Fakten · 12 Min. Lesezeit
Quelle: dev.to
Rubrik: Sichere Programmierung




What is an Array in Go?



In Go, an array is a fixed-size, ordered set of values with the same type. Imagine an array as a 12 egg tray; the minimum number of eggs which can fit into an array is 12; the maximum number of eggs which can fit into an array is 12. That is the exact behaviour of a Go array.




package main
​
import "fmt"
​
func main() {

var groceries [3]string// Step 1: Create an array that holds 3 strings
groceries[0] = "Bread"// Step 2: Put "Bread" in slot 0
groceries[1] = "Milk"// Step 3: Put "Milk" in slot 1
groceries[2] = "Eggs"// Step 4: Put "Eggs" in slot 2
fmt.Println(groceries)// Step 5: Print the whole array
}






Expected output:

[Bread Milk Eggs]





Zero Values



In Go, you create an array by using the var keyword, and each of the slots receives the safe code Zero value, given that no elements are explicitly set.





This means that your array will never be in an unsafe state of being uninitialized. It will be valid on every slot, even before set. The same thing is a safety feature in Go intentionally.




var prices [3]float64

fmt.Println(prices) // Output: [0 0 0] - Go fills all the values with zeros automatically









Declaring an Array



In Go, you can declare an array in a few different ways, and you will learn about each of them in turn.






Using the var Declaration






var groceries [3]string
groceries[0] = "Bread"
groceries[1] = "Milk"
groceries[2] = "Eggs"






If you want to initialise an array of a specific size and use it later, then this is the best method to achieve this.






Array Literals



If you are already aware of all the values at the time you write the code, then you can use the literal syntax:




package main

import "fmt"

func main() {
groceries := [3]string{"Bread", "Milk", "Eggs"}
fmt.Println(groceries)
}






Expected output:

[Bread Milk Eggs]



The actual syntax is:

[size]type{value1, value2, value3}

This method is used when we know the values which we want to store in an array.





Let the Compiler count for you — The ... trick



When using literal syntax, and you find that you have to manually count yourself, there's a shortcut in Go. Use ... to fill the size so the compiler can calculate the length automatically.




groceries := [...]string{"Bread", "Milk", "Eggs", "Butter", "Coffee"} //Three dots  compiler counts for you






The type of groceries is [5]string. The ... instructs the compiler to count for you. This will be helpful if you have a super long list and you can't determine its length.






Sparse Initialization



You can also use index: value syntax in the braces: to specify where a value will go:




package main
​
import "fmt"
​
func main() {
// Put "Bread" in slot 0 and "Coffee" in slot 4; all other slots get ""
groceries := [5]string{0: "Bread", 4: "Coffee"}
fmt.Println(groceries)
}






​

Expected output:

[Bread Coffee]



This is helpful when you have an array of a large number of elements, but just a couple of elements to change.





How to access elements and modify an array.



Each element of an array is retrieved by the array name and an index number enclosed in square brackets.




package main

import "fmt"

func main() {

groceries := [3]string{"Bread", "Milk", "Eggs"}

fmt.For each element, read it on the screen:
Println(groceries[0])// Read "Bread" on the screen
fmt.Println(groceries[2])// Read slot 2: Eggs
groceries[0] = "Brown Bread" // Change the value of the 0th element of the array.
fmt.Println(groceries[0])// Read slot 0 again → "Brown Bread"
}






Expected output:




Bread
Eggs
Brown Bread









What are the consequences of going beyond the lines?



If you try to access a non-existent part of a structure (for example, groceries[5] for a 3-element array), then Go will immediately exit the program with a runtime panic:

runtime error: index out of range [5] with length 3

Not a silent bug this time. Go lets you know what was amiss. len(array) - 1 is the final valid index in the array.





Getting the Length with len()



len() returns the size (number of slots) of an array:




package main

import "fmt"

func main() {
groceries := [5]string{"Bread", "Milk", "Eggs", "Butter", "Coffee"}
fmt.Println("Items on list:", len(groceries))
}






Expected output:

Items on list: 5



If an array is declared with a size, then len() always returns the exact size, irrespective of whether there are values stored in some of the array's slots. An array is always the size that it was created to be.



Also, there is an operation cap(), which is called "capacity". Arrays cannot be lengthened or shortened, but the two functions, cap() and len(), return the same value. Use len(arr) instead of literals for the size. If you ever change the array declaration, len() adjusts automatically.



When the array is of length, len() always returns the size (independent of whether or not there are zeroes in the array). An array is always allocated the memory space it was declared to have.





Arrays are valued, not references.



As a result of Go's copy behavior on assigning an array to a new variable, the entire array is copied. There are two independent variables – if one changes, the other one definitely will not change at all. Let's say we think of an example;




package main
​
import "fmt"
​
func main() {
groceries := [3]string{"Bread", "Milk", "Eggs"}
backup := groceries// This copies ALL of groceries into backup
​
groceries[0] = "Brown Bread"// Change the original
​
fmt.Println("groceries:", groceries)
fmt.Println("backup:", backup)
}






​

Expected output:




groceries: [Brown Bread Milk Eggs]
backup:[Bread Milk Eggs]







The above shows that despite replacing groceries [0] with ‘Brown Bread’, backup was not affected. This is similar to photocopying your shopping list! After they've made the photocopy, it remains unchanged if they write on the original. They started identical, but are now two completely separate pieces of paper.






Sharing With Pointers



If we want, the changes that we make with our new variable to affect the original array, it's using a pointer.




package main
​
import "fmt"
​
func main() {
groceries := [3]string{"Bread", "Milk", "Eggs"}
shared := &groceries// & means "give me the address of groceries"
​
groceries[0] = "Brown Bread"
​
fmt.Println("groceries:", groceries)
fmt.Println("shared:", *shared)// * means "follow the pointer to the value"
}






​

Expected output:




groceries: [Brown Bread Milk Eggs]
shared:[Brown Bread Milk Eggs]






&groceries make a pointer. You don't copy the array; you copy a small "address" indicating where the array is stored in memory. That is followed by the word ‘*shared follows that address to get the actual value. When Shared access is needed, Pointers are used. In most situations, you'll opt for the default copy behaviour, which is more secure and easier to do.






Comparing Arrays



Go and share how you can use “==” and “!=” to compare two arrays of equal “size” and “type”.




package main
​
import "fmt"
​
func main() {
list1 := [3]string{"Bread", "Milk", "Eggs"}
list2 := [3]string{"Bread", "Milk", "Eggs"}
list3 := [3]string{"Bread", "Milk", "Coffee"}
​
fmt.Println("Same?", list1 == list2)// true
fmt.Println("Same?", list1 == list3)// false
}






​

Expected output:




Same? true
Same? false







Two arrays are equal if they are of the same type and length and the elements of the arrays in the corresponding positions are all equal. You must have both conditions.

Comparison of differently sized arrays is not possible. The compiler will halt you, since they are of different types.



Looping Through Arrays

For small arrays, manually writing the below would work: groceries[0], groceries[1], groceries[2]. Anything larger, you just use a loop to visit each element by itself. Some of the loops you can use to accomplish this are listed here:





The for range Loop



The most popular looping over an array in Go is the following for range loop:




package main
import "fmt"
func main() {
groceries := [5]string{"Bread", "Milk", "Eggs", "Butter", "Coffee"}
For each element (index, item) in the groceries: {
fmt.println("Index: " + index + " Item: " + item)
}
}






Expected output:




Index: 0 Item: Bread
Index: 1 Item: Milk
Index: 2 Item: Eggs
Index: 3 Item: Butter
Index: 4 Item: Coffee






The index will contain the number of the slot that is being modified on each iteration through the loop, and the item will contain a copy of the element being modified. The loop stops by itself when it runs out of elements. No more worrying about out of bounds.



In Go programming, all the variables defined must be used. The for-range loop provides Go with two variables in its "for" clause: the index and element variable. If the index isn’t useful to you, then you can't just leave it there intact. It will refuse to compile with Go.



This is where the blank identifier _ is introduced. It is Go's way of letting you say, "I know this value exists, but I am deliberately throwing it away."




package main
​
import "fmt"
​
func main() {
groceries := [5]string{"Bread", "Milk", "Eggs", "Butter", "Coffee"}
​
for _, item := range groceries {
fmt.Println("Item:", item)
}
}






Expected output:




Item: Bread
Item: Milk
Item: Eggs
Item: Butter
Item: Coffee






It's also possible to discard the value and keep the index. If so, simply do not use the second variable at all:




For each index in the groceries array {
fmt.Println("Index:", index)
}









A classic for Loop.



In the case where you require more control, such as when going in reverse or skipping an element, the classic counter-based for loop is best:




package main
​
import "fmt"
​
func main() {
groceries := [5]string{"Bread", "Milk", "Eggs", "Butter", "Coffee"}
​
for i := 0; i < len(groceries); i++ {
fmt.Println("Position", i, "->", groceries[i])
}
}






​

Expected output:




Position 0 -> Bread
Position 1 -> Milk
Position 2 -> Eggs
Position 3 -> Butter
Position 4 -> Coffee






​

Iterating in reverse:




for i := len(groceries) - 1; i >= 0; i-- {
fmt.Println(groceries[i])
}

//`Output: Coffee → Butter → Eggs → Milk → Bread`






Printing every other item:




for i := 0; i < len(groceries); i += 2 {
fmt.Println(groceries[i])
}

//`Output: Bread → Eggs → Coffee (slots 0, 2, and 4)`









Multi-Dimensional Arrays



So far, all the arrays have been a single row of values (one-dimensional). Multi-dimensional arrays (arrays of arrays) are also supported in Go.

The most common case is a 2D array, which is a grid or a table. For instance, if I go to the shops every week and make a plan for the items I want to buy by each day and area of the shop:




package main
​
import "fmt"
​
func main() {
// A 3-day plan with 2 items per day
weeklyPlan := [3][2]string{
{"Bread", "Milk"},// Day 0
{"Eggs", "Butter"},// Day 1
{"Coffee", "Fruit"},// Day 2
}
​
for day, items := range weeklyPlan {
fmt.Printf("Day %d: %s and %s\n", day, items[0], items[1])
}
}

Day 0: Bread and Milk
Day 1: Eggs and Butter
Day 2: Coffee and Fruit






[3][2]string: An array of 3 elements, each of which is an array of 2 strings. The first index tells you which row to choose, the second index tells you which column to choose:




weeklyPlan[0][0] = "Bread"// Day 0, first item
weeklyPlan[0][1] = "Milk"// Day 0, second item
weeklyPlan[2][1] = "Fruit"// Day 2, second item






An index position is needed to reference a particular cell, the first being the row index, and the second, the column index.

passing an Array object to a function.

In Go, an array passed to a function is itself a complete copy of the array; the function does not refer to the original array. Any changes the function makes don't affect the original:




package main
​
import "fmt"
​
func printAndModify(list [3]string) {
list[0] = "Changed"// Modifies the LOCAL copy only
fmt.Println("Inside:", list)
}
​
func main() {
groceries := [3]string{"Bread", "Milk", "Eggs"}
printAndModify(groceries)
fmt.Println("Outside:", groceries)// Original is unchanged
}






​

Expected output:




Inside: [Changed Milk Eggs]
Outside: [Bread Milk Eggs]






The function takes a snapshot of an array that is independent of one another.

If you have to change the original function, provide a pointer:




package main
​
import "fmt"
​
func updateFirstItem(list *[3]string) {
list[0] = "Brown Bread"// This modifies the original
}
​
func main() {
groceries := [3]string{"Bread", "Milk", "Eggs"}
updateFirstItem(&groceries)
fmt.Println("Outside:", groceries)// Now the original IS changed
}






​

Expected output:

Outside: [Brown Bread Milk Eggs]



If you have a large array greater than a few hundred elements, always use a pointer instead of copying to avoid the cost of the copy.





Limitations of Arrays



Though concise and straightforward, arrays are restricted in their use and come with limitations that you'll hit hard soon.





The Size Is Fixed Forever



After defining a [3]string, it will always contain exactly 3 strings, always! You can't add a fourth item. You can't remove one to shrink it. The size is baked in at compile time. If your shopping list grows to 6 items, your [5]string array can't help you.

The array size can not be a variable, must be a literal number or named constant:




n := 5
var groceries [n]string






The above is a compiler error because of the occurrence of the variable n.




Fix:
const n = 5
var groceries [n]string// it Works, n is a constant






This means you can't create an array whose size depends on something you only know at runtime, like how many items the user typed in. For that, you need a slice.






Passing Large Arrays Is Expensive



Every function call copies the entire array. For a [10000]string, that is 10,000 strings copied just to call a function.

Arrays of Different Sizes Are Incompatible Types

A function that accepts [3] strings can't be called with a [5]string. You would need two separate functions with different signatures.

append() Does Not Work on Arrays

append() — the function that adds elements to a collection — only works on slices, not arrays:




groceries := [3]string{"Bread", "Milk", "Eggs"}
groceries = append(groceries, "Butter")// Compiler `error`: append expects a slice






​

These limitations are not bugs. Fixed-size value types are simple, predictable, and give the compiler strong guarantees. But most real-world programming needs something that can grow and shrink at runtime. That something is the slice.





Common Mistakes with Arrays





Mistake 1: Assigning Arrays of Different Sizes





list := [3]string{"Bread", "Milk", "Eggs"}
var biggerList [4]string = list// Compiler `error` — different types





​

Fix: make sure both arrays have the same size, or use a slice if you need flexibility.

​





Mistake 2: Expecting Assignment to Share Data





list := [3]string{"Bread", "Milk", "Eggs"}
backup := list
backup[0] = "Brown Bread"
fmt.Println(list[0])// Prints "Bread", NOT "Brown Bread" — list was not changed





Arrays are value types. Assignment copies everything. If you want shared access, use &list to get a pointer, or switch to slices.



Mistake 3: Off-by-One on the Last Element




groceries := [3]string{"Bread", "Milk", "Eggs"}
fmt.Println(groceries[3])// Runtime `panic`: index out of range






For an array of length 3, the valid indexes are 0, 1, and 2. The last valid index is always len(array) - 1.

Social ReaktionenReagiere als Erste:r — dein Feedback zählt!
Informations-Bewertung:
✏️ Information ergänzen
🛡️ Versioniert via CMS-Revisions-Engine (Freigabe-Queue für Gäste)

💬 Topluluk tartışması ve yorumlar

🌐 Ana sohbete katıl

Tartışmayı başlat: Social Chat yayın akışı veya yukarıdaki ekleme formuyla uzman katkısı gönder.

Security Briefing Ücretsiz · Tek tıkla abonelikten çıkma

Zeka Digest - ücretsiz

Günlük en önemli güvenlik haberi · herhangi bir zamanda alınabilir

Community Rating &amp; Social Proof
⭐ Okuyucu Puanı
–
Ø / 5.0
Hiçbir okuyucu henüz yorum yok
Bu makale yararlı mıydı?
0
Değerlendirmenizi gönderin
Detaylı değerlendirme (isteğe bağlı)
İçerik ve Kalite
Kaynak ve Güvenilirlik
Güncellik

İlgili Story Cluster & Kaynaklar (vector AI)

6 Cluster
21 Kaynaklar
CVE-2026-129373 | Joomla! Project Joomla Extension 1.6.0-5.4.10/6.0.0-6.2.0 Password Reset session expiration (EUVD-2026-134294)
VulDB Updates 42 dakika önce
20 diğer kaynaklar
VulDB Updates42 dakika önceCVE-2026-129385 | Joomla! Project Joomla! Extension 4.0.0-5.4.10/6.0.0-6.2.0 Mail Template information disclosure (EUVD-2026-134295) VulDB Updates42 dakika önceCVE-2026-129381 | Joomla! Project Joomla Extension up to 5.4.10/6.2.0 Install From Web cross-site request forgery (EUVD-2026-134293) VulDB Updates42 dakika önceCVE-2026-127299 | Joomla! Project Joomla Extension up to 1.6.0/5.4.10/6.0.0/6.2.0 com_newsfeeds name cross site scripting (EUVD-2026-134290) VulDB Updates42 dakika önceCVE-2026-123210 | Joomla! Project Joomla Extension 4.0.0-5.4.10/6.0.0-6.2.0 com_media input validation (EUVD-2026-134291) VulDB Updates32 dakika önceCVE-2026-126045 | Joomla! Project Joomla Extension up to 1.6.0/5.4.10/6.0.0/6.2.0 Language Parameter language file inclusion (EUVD-2026-134289) VulDB Updates32 dakika önceCVE-2026-129387 | Joomla! Project Joomla! CMS Extension 4.0.0-5.4.10/6.0.0-6.2.0 com_menus privileges management (EUVD-2026-134288) VulDB Updates32 dakika önceCVE-2026-127300 | Joomla! Project Joomla CMS Extension 4.3.0-5.4.10/6.0.0-6.2.0 com_guidedtours cross site scripting (EUVD-2026-134285) VulDB Updates32 dakika önceCVE-2026-127295 | Joomla! Project Joomla Extension 4.0.0-5.4.10/6.0.0-6.2.0 Webservice Endpoints permission (EUVD-2026-134286) VulDB Updates32 dakika önceCVE-2026-129383 | Joomla! Project Joomla Extension 6.2.0 SMTP OAuth2 Settings information disclosure (EUVD-2026-134287) VulDB Updates32 dakika önceCVE-2026-129382 | Joomla! Project Joomla Extension up to 5.4.10/6.2.0 com_media permission (EUVD-2026-134284) VulDB Updates32 dakika önceCVE-2026-127297 | Joomla! Project Joomla 3.6.0-5.4.10/6.0.0-6.2.0 Formatted Text Logger race condition (EUVD-2026-134282) VulDB Updates32 dakika önceCVE-2026-129389 | Joomla! Project Joomla Extension up to 3.8.3/5.4.10/6.0.0/6.2.0 Wrapper cross site scripting (EUVD-2026-134283) VulDB Updates32 dakika önceCVE-2026-127296 | Joomla! Project Joomla CMS Extension 4.0.0-5.4.10/6.0.0-6.2.0 com_config information disclosure (EUVD-2026-134281) VulDB Updates1 saat önceCVE-2026-127298 | Joomla! Project Joomla Extension up to 1.6.0/5.4.10/6.0.0/6.2.0 com_contact name cross site scripting (EUVD-2026-134302) VulDB Updates1 saat önceCVE-2026-129368 | Joomla Extension 1.6.0-5.4.10/6.0.0-6.2.0 Banner cross site scripting (EUVD-2026-134300) VulDB Updates1 saat önceCVE-2026-129386 | Joomla! Project Joomla Extension 1.6.0-5.4.10/6.0.0-6.2.0 com_contact privileges management (EUVD-2026-134301) VulDB Updates1 saat önceCVE-2026-129388 | Joomla! Project Joomla! Extension 4.0.0-5.4.10/6.0.0-6.2.0 com_media path traversal (EUVD-2026-134298) VulDB Updates1 saat önceCVE-2026-127304 | Joomla Extension 3.9.0-5.4.10/6.0.0-6.2.0 Custom Fields showon cross site scripting (EUVD-2026-134299) VulDB Updates1 saat önceCVE-2026-123214 | Joomla! Project Joomla Extension 4.0.0-5.4.10/6.0.0-6.2.0 Web Installer missing authentication (EUVD-2026-134297) VulDB Updates1 saat önceCVE-2026-129365 | Joomla! Project Joomla Extension up to 2.5.10/5.4.10/6.0.0/6.2.0 com_installer cross site scripting (EUVD-2026-134296)
13 Kaynaklar
Square POS Black Friday deals: save up to $291 on three small business systems at Best Buy
Latest from TechRadar 31 dakika önce
12 diğer kaynaklar
13 Kaynaklar
ZDI-26-1078: llama.cpp GGUF File Parsing MINICPM-V Heap-based Buffer Overflow Remote Code Execution Vulnerability
ZDI: Published Advisories 14 saat önce
12 diğer kaynaklar
ZDI: Published Advisories14 saat önceZDI-26-1071: llama.cpp GGUF File Parsing Integer Overflow Remote Code Execution Vulnerability ZDI: Published Advisories14 saat önceZDI-26-1077: llama.cpp GGUF File Parsing HunyuanVL Heap-based Buffer Overflow Remote Code Execution Vulnerability ZDI: Published Advisories14 saat önceZDI-26-1076: llama.cpp Multimodal GGUF File Parsing Out-Of-Bounds Write Remote Code Execution Vulnerability ZDI: Published Advisories14 saat önceZDI-26-1075: llama.cpp GGUF File Parsing set_swa_pattern Heap-based Buffer Overflow Remote Code Execution Vulnerability ZDI: Published Advisories14 saat önceZDI-26-1073: llama.cpp MTMD Multimodal GGUF File Parsing Out-Of-Bounds Read Denial-of-Service Vulnerability ZDI: Published Advisories14 saat önceZDI-26-1074: llama.cpp GGUF File Parsing GEMMA4A Heap-based Buffer Overflow Remote Code Execution Vulnerability ZDI: Published Advisories14 saat önceZDI-26-1072: llama.cpp GGUF File Parsing Integer Overflow Denial-of-Service Vulnerability ZDI: Published Advisories14 saat önceZDI-26-1056: (0Day) PyTorch Foundation PyTorch PT2 File Parsing Exposed Dangerous Method Remote Code Execution Vulnerability ZDI: Published Advisories14 saat önceZDI-26-1048: (0Day) Soda PDF Desktop PDF File Parsing Memory Corruption Remote Code Execution Vulnerability ZDI: Published Advisories14 saat önceZDI-26-1050: (0Day) Soda PDF Desktop PDF File Parsing Memory Corruption Remote Code Execution Vulnerability ZDI: Published Advisories14 saat önceZDI-26-1052: (0Day) PyTorch Foundation PyTorch PT2 File Parsing Code Injection Remote Code Execution Vulnerability ZDI: Published Advisories14 saat önceZDI-26-1049: (0Day) Soda PDF Desktop PDF File Parsing Out-Of-Bounds Write Remote Code Execution Vulnerability
Benzer katkılar
🔍 Verwandte News

Auch interessante Nachrichten Array in Go

Thematisch verwandte Begriffe: Array · 6 Treffer

Laden...

Videolar yükleniyor...

Laden...

Contributions yüklenir ...

Laden...

Videolar yükleniyor...

Yorumlar yüklenir..
Update to Update
Widgets & Topics
Loading widgets…
Nächster Beitrag