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

推荐订阅源

Security Archives - TechRepublic
Security Archives - TechRepublic
Project Zero
Project Zero
K
Kaspersky official blog
G
Google Developers Blog
T
Threat Research - Cisco Blogs
T
The Blog of Author Tim Ferriss
Cyberwarzone
Cyberwarzone
Y
Y Combinator Blog
Recorded Future
Recorded Future
Blog — PlanetScale
Blog — PlanetScale
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Cisco Talos Blog
Cisco Talos Blog
Latest news
Latest news
Microsoft Security Blog
Microsoft Security Blog
H
Help Net Security
S
Schneier on Security
P
Palo Alto Networks Blog
H
Hacker News: Front Page
N
News and Events Feed by Topic
N
Netflix TechBlog - Medium
博客园 - Franky
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
SecWiki News
SecWiki News
Cloudbric
Cloudbric
TaoSecurity Blog
TaoSecurity Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
The Hacker News
The Hacker News
C
Check Point Blog
L
LangChain Blog
腾讯CDC
小众软件
小众软件
T
Tenable Blog
Google DeepMind News
Google DeepMind News
GbyAI
GbyAI
L
LINUX DO - 最新话题
A
About on SuperTechFans
Google Online Security Blog
Google Online Security Blog
C
Cisco Blogs
Recent Announcements
Recent Announcements
Hacker News: Ask HN
Hacker News: Ask HN
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Vercel News
Vercel News
雷峰网
雷峰网
美团技术团队
D
DataBreaches.Net
Martin Fowler
Martin Fowler
Help Net Security
Help Net Security
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
F
Full Disclosure
博客园_首页

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
Go Compiler & defer: Bootstrap, Three defer Implementations, panic/recover & Closures
James Lee · 2026-05-19 · via DEV Community

Go's compiler is written entirely in Go — a self-hosting compiler that handles everything from frontend parsing to backend code generation. In this article we'll trace the program lifecycle from the very first instruction, dig into how defer is implemented in three different ways, and cover the panic/recover model, build tags, and the infamous closure-in-loop trap.


1. The Go Compiler Pipeline

Source (.go)
    ↓
Lexer / Parser       → AST
    ↓
Type Checker         → typed AST
    ↓
IR (SSA)             → optimizations, escape analysis
    ↓
Code Generation      → machine code
    ↓
Linker               → binary

Enter fullscreen mode Exit fullscreen mode

The entire pipeline — from frontend to backend — is implemented in Go itself. No C, no LLVM (by default).

Performance Tooling

Before optimizing, always measure:

Tool What it shows
go tool pprof CPU, memory, goroutine profiles — µs-level code hotspots
go tool trace Runtime events: goroutine scheduling, GC, netpoller — ns-level

Optimization priority:

Storage layer (ms gains) > Business logic (µs gains) > Low-level code (ns gains)

Enter fullscreen mode Exit fullscreen mode

Optimization workflow:

  1. Load test with realistic traffic
  2. pprof → identify CPU/memory hotspots
  3. Fix: async, cache, algorithm change
  4. benchmark → verify local improvement
  5. Repeat load test → check p95 latency

2. Program Bootstrap: From rt0_amd64 to main.main

Your Go program does not start at main.main. It doesn't even start at runtime.main. The real entry point is deep in the runtime assembly.

runtime.rt0_amd64          ← actual binary entry point
    ↓
runtime.rt0_go             ← determine CPU core count + physical page size
    ↓
runtime.schedinit()        ← initialize: scheduler, stack allocator,
    ↓                         memory allocator, GC
runtime.newproc(main)      ← create main goroutine, push to P's LRQ
    ↓
runtime.mstart()           ← start M0, enter scheduling loop (never returns)
    ↓
runtime.main()             ← main goroutine starts here

Enter fullscreen mode Exit fullscreen mode

runtime.main() execution order:

func main() {
    // 1. Set max stack size: 1GB (64-bit) / 250MB (32-bit)
    maxstacksize = 1000000000

    // 2. Start sysmon background thread (GC, preemption, netpoll)
    systemstack(func() { newm(sysmon, nil) })

    // 3. Initialize runtime packages
    runtime_init()

    // 4. Enable GC background workers
    gcenable()

    // 5. Run all init() functions in imported packages
    main_init()

    // 6. Run user's main.main()
    main_main()

    // 7. Exit
    exit(0)
}

Enter fullscreen mode Exit fullscreen mode

Key difference: Non-main goroutines return to goexit when done. The main goroutine calls exit(0) — terminating the entire process immediately.


3. defer: Three Implementation Strategies

defer looks like a simple "run this at function exit" mechanism. The reality is more nuanced — Go uses three different implementations depending on the context, each with different performance characteristics.

Why not just insert a function call at return?

Because defer can appear inside conditionals and loops, the compiler cannot always statically determine how many defers exist or which ones will execute. This makes a purely compile-time solution insufficient.


Strategy 1: Heap Allocation (General Case)

Each defer creates a _defer struct allocated on the heap, chained into the goroutine's defer linked list.

// Compiler transforms:
defer foo()
// Into:
deferproc(foo)   // allocate _defer on heap, push to G._defer list
...
deferreturn()    // at function exit: walk list, execute defers in LIFO order

Enter fullscreen mode Exit fullscreen mode

type _defer struct {
    siz       int32      // size of arguments + return values
    sp        uintptr    // stack pointer at defer site
    pc        uintptr    // caller's program counter
    fn        *funcval   // the deferred function
    link      *_defer    // next defer in chain (linked list)
}

type g struct {
    _defer *_defer       // head of this goroutine's defer list
}

Enter fullscreen mode Exit fullscreen mode

Cost: Heap allocation per defer call. Slowest strategy.


Strategy 2: Stack Allocation (Go ≥ 1.13)

When the compiler can prove a defer is not in a loop and the number is bounded, it allocates the _defer struct on the stack instead of the heap.

// Compiler allocates _defer directly in the function's stack frame
t := deferstruct(stksize)   // stack-allocated _defer
// ... initialize fields ...
deferreturn()

Enter fullscreen mode Exit fullscreen mode

Cost: No heap allocation. Significantly faster than heap strategy.


Strategy 3: Open-Coded (Go ≥ 1.14, Most Common)

When all conditions are met, the compiler inlines the deferred calls directly at each return site, using a bitmask (deferBits) to track which defers should fire.

Conditions for open-coded defer:

  • Compiler optimizations not disabled (-gcflags "-N" not set)
  • ≤ 8 defers in the function
  • num_defers × num_returns ≤ 15
  • No defer inside a loop
// Source:
defer f1(a1)
if cond {
    defer f2(a2)
}

// Compiler generates:
deferBits = 0b00000000
deferBits |= 1 << 0     // f1 is always deferred → bit 0 set
_f1, _a1 = f1, a1
if cond {
    deferBits |= 1 << 1 // f2 conditionally deferred → bit 1 set
    _f2, _a2 = f2, a2
}

// At every return site (reverse order):
if deferBits & (1<<1) != 0 {
    deferBits &^= (1 << 1)
    _f2(_a2)
}
if deferBits & (1<<0) != 0 {
    deferBits &^= (1 << 0)
    _f1(_a1)
}

Enter fullscreen mode Exit fullscreen mode

Cost: Near-zero — just a few bit operations and direct calls. No allocation.

Not truly zero-cost: Arguments are evaluated and copied to the stack at the defer site. Conditional defers still need the deferBits check at runtime.


defer Gotchas

Gotcha 1: Arguments are evaluated immediately

// Prints "0s" — time.Since() is evaluated when defer is registered
func main() {
    startedAt := time.Now()
    defer fmt.Println(time.Since(startedAt))
    time.Sleep(time.Second)
}

// Prints "1s" — time.Since() is evaluated when the closure runs
func main() {
    startedAt := time.Now()
    defer func() { fmt.Println(time.Since(startedAt)) }()
    time.Sleep(time.Second)
}

Enter fullscreen mode Exit fullscreen mode

Gotcha 2: Not all builtins can be deferred directly

// ❌ Cannot defer directly:
defer append(sl, 1)
defer cap(sl)
defer len(sl)

// ✅ Wrap in a closure:
defer func() { _ = append(sl, 1) }()

// ✅ Can defer directly:
defer close(ch)
defer delete(m, key)
defer recover()

Enter fullscreen mode Exit fullscreen mode

Gotcha 3: Use anonymous functions to scope locks precisely

func someFunc() {
    // ... lots of code ...
    func() {
        mu.Lock()
        defer mu.Unlock()
        // critical section — lock released at end of anonymous func,
        // not at end of someFunc
    }()
    // ... more code runs without holding the lock ...
}

Enter fullscreen mode Exit fullscreen mode


4. panic / recover Internals

Mental Model

Go Java equivalent
panic RuntimeException + Error
recover catch (but only inside defer)

Key rule: recover only works inside a defer function. It catches panics propagated via runtime.panic(), but not runtime.throw() or runtime.fatal() (which are unrecoverable runtime errors).

Data Structures

type _panic struct {
    arg       interface{}  // value passed to panic()
    link      *_panic      // previous panic in chain
    recovered bool         // has this panic been recovered?
    aborted   bool         // has this panic been aborted?
}

type g struct {
    _panic *_panic   // head of panic chain (innermost first)
    _defer *_defer   // head of defer chain (innermost first)
}

Enter fullscreen mode Exit fullscreen mode

gopanic Execution Flow

panic(val) called
    ↓
gopanic():
    allocate _panic on stack
    prepend to g._panic list
        ↓
    loop: walk g._defer list
        ↓
        execute each defer function
            ↓
            defer contains recover()?
                ├── YES: p.recovered = true
                │         mcall(recovery) → re-enter scheduler  ✅
                │         gopanic exits here
                └── NO:  continue to next defer
        ↓
    no more defers, p.recovered still false
        ↓
    preprintpanics() → print stack trace
    fatalpanic()     → terminate process  💥

Enter fullscreen mode Exit fullscreen mode

// Minimal recover pattern:
func safeCall() {
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("recovered:", r)
        }
    }()
    panic("something went wrong")
}

Enter fullscreen mode Exit fullscreen mode

Panic is not for normal error handling. Use error returns for expected failures. Reserve panic for truly unrecoverable states (programmer errors, invariant violations).


5. Build Tags

Build tags control which files are included in compilation — at the file level, not the code block level.

// dev.go
//go:build dev
package main

func init() {
    configArr = append(configArr, "mysql dev")
}

Enter fullscreen mode Exit fullscreen mode

// prod.go
//go:build prod
package main

func init() {
    configArr = append(configArr, "mysql prod")
}

Enter fullscreen mode Exit fullscreen mode

go build -tags "dev"   # includes dev.go, excludes prod.go
go build -tags "prod"  # includes prod.go, excludes dev.go

Enter fullscreen mode Exit fullscreen mode

Common use cases: environment-specific config, OS-specific implementations, feature flags, test fixtures.


6. Closures & the Goroutine Loop Trap

A closure captures variables by reference, not by value. This creates a classic bug when launching goroutines inside a loop.

The Trap

// ❌ All goroutines process the LAST node
for i := range nodes {
    go func() {
        node := nodes[i]  // i is shared — by the time goroutine runs,
        process(node)     // the loop has already advanced i
    }()
}

Enter fullscreen mode Exit fullscreen mode

The Fix

// ✅ Capture a local copy of i at each iteration
for i := range nodes {
    index := i            // new variable per iteration
    go func() {
        node := nodes[index]  // each goroutine has its own index
        process(node)
    }()
}

// ✅ Or pass as argument (cleaner):
for i := range nodes {
    go func(idx int) {
        node := nodes[idx]
        process(node)
    }(i)
}

Enter fullscreen mode Exit fullscreen mode

Go 1.22+ changed loop variable semantics: each iteration now creates a new variable, making the first pattern safe. But for pre-1.22 compatibility, always capture explicitly.


7. Summary

Topic Key Takeaway
Bootstrap Entry: rt0_amd64schedinitnewproc(main)mstart
defer (heap) _defer on heap, linked list on G — slowest, most general
defer (stack) _defer in stack frame — faster, no heap alloc
defer (open-coded) Inlined at return sites with deferBits bitmask — near-zero cost
defer args Evaluated at defer registration, not at execution
panic/recover gopanic walks defer chain; recover sets p.recovered; mcall(recovery) re-enters scheduler
Build tags File-level inclusion/exclusion at compile time
Closure trap Loop variables are shared; always capture a local copy for goroutines

This concludes the Go Runtime Internals series. You now have a complete picture of how Go manages memory, I/O, system calls, scheduling, and language-level features like defer and panic — all the way down to the assembly level.


Found this series useful? Share it with your team and follow for more Go deep dives.