惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

S
Schneier on Security
Recent Announcements
Recent Announcements
C
Check Point Blog
Stack Overflow Blog
Stack Overflow Blog
Vercel News
Vercel News
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
A
About on SuperTechFans
爱范儿
爱范儿
D
DataBreaches.Net
The GitHub Blog
The GitHub Blog
L
LangChain Blog
大猫的无限游戏
大猫的无限游戏
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
云风的 BLOG
云风的 BLOG
月光博客
月光博客
AI
AI
美团技术团队
SecWiki News
SecWiki News
WordPress大学
WordPress大学
N
Netflix TechBlog - Medium
V
Vulnerabilities – Threatpost
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
C
Cybersecurity and Infrastructure Security Agency CISA
M
MIT News - Artificial intelligence
PCI Perspectives
PCI Perspectives
aimingoo的专栏
aimingoo的专栏
D
Darknet – Hacking Tools, Hacker News & Cyber Security
V
Visual Studio Blog
T
The Exploit Database - CXSecurity.com
小众软件
小众软件
N
News | PayPal Newsroom
阮一峰的网络日志
阮一峰的网络日志
人人都是产品经理
人人都是产品经理
NISL@THU
NISL@THU
Hacker News: Ask HN
Hacker News: Ask HN
Security Latest
Security Latest
MongoDB | Blog
MongoDB | Blog
H
Heimdal Security Blog
Schneier on Security
Schneier on Security
B
Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
B
Blog RSS Feed
D
Docker
Spread Privacy
Spread Privacy
Cloudbric
Cloudbric
www.infosecurity-magazine.com
www.infosecurity-magazine.com
I
Intezer
T
The Blog of Author Tim Ferriss
Last Week in AI
Last Week in AI
AWS News Blog
AWS News Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Array in Go
Frihk Ian · 2026-06-24 · via DEV Community

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.