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

推荐订阅源

F
Fortinet All Blogs
有赞技术团队
有赞技术团队
量子位
N
Netflix TechBlog - Medium
博客园 - 叶小钗
博客园 - 三生石上(FineUI控件)
Google DeepMind News
Google DeepMind News
aimingoo的专栏
aimingoo的专栏
GbyAI
GbyAI
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Blog — PlanetScale
Blog — PlanetScale
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
月光博客
月光博客
Martin Fowler
Martin Fowler
Y
Y Combinator Blog
宝玉的分享
宝玉的分享
博客园 - 司徒正美
云风的 BLOG
云风的 BLOG
V
Visual Studio Blog
V
V2EX
IT之家
IT之家
L
LangChain Blog
大猫的无限游戏
大猫的无限游戏
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More

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
🤨 Go Quiz — Slices, Pointers, Structs & Decimal
Ponlamai · 2026-05-06 · via DEV Community

Ponlamai

A collection of Go quizzes to test your understanding of slices, pointers, structs, and decimals. Try to answer before revealing each answer!


Slice #1

func main() {
    var a []int
    for i := 1; i <= 5; i++ {
        a = append(a, i)
        fmt.Printf("%p, %p, %d, %d\n", &a, &a[0], len(a), cap(a))
    }
}

Enter fullscreen mode Exit fullscreen mode

Question

Consider the result of line 5 for each iteration.

  1. Will the address of a be identical?
  2. Will the address of a[0] be identical?
  3. What is the expected len(a)?
  4. What is the expected cap(a)?
Answer
0xc000010018, 0xc000012028, 1, 1
0xc000010018, 0xc000012050, 2, 2
0xc000010018, 0xc00007a020, 3, 4
0xc000010018, 0xc00007a020, 4, 4
0xc000010018, 0xc00007c040, 5, 8

Enter fullscreen mode Exit fullscreen mode

  • The address of a (the slice header) is always the same — the variable itself doesn't move.
  • The address of a[0] changes when the backing array is reallocated (capacity exceeded).
  • cap doubles each time a reallocation happens: 1 → 2 → 4 → 8.

Reference: https://go.dev/blog/slices-intro


Slice #2

func main() {
    a := []int{1, 2, 3, 4, 5, 6, 7}
    b := make([]int, 5, 5)
    for _, i := range a {
        b = append(b, i)
    }
    fmt.Println(b, len(b), cap(b))   // line 7
    fmt.Println(b[19])               // line 8
    c := b[:20]
    fmt.Println(c, len(c), cap(c))   // line 10
    c[11] = 99
    fmt.Println(b, c)                // line 12
    c[19] = 99
    fmt.Println(b, c)                // line 14
}

Enter fullscreen mode Exit fullscreen mode

Question

Determine the expected output of lines 7, 8, 10, 12, 14.

Answer
// line 7:  [0 0 0 0 0 1 2 3 4 5 6 7] 12 20
// line 8:  panic!
// line 10: [0 0 0 0 0 1 2 3 4 5 6 7 0 0 0 0 0 0 0 0] 20 20
// line 12: b=[0 0 0 0 0 1 2 3 4 5 6 99]  c=[0 0 0 0 0 1 2 3 4 5 6 99 0 0 0 0 0 0 0 0]
// line 14: b=[0 0 0 0 0 1 2 3 4 5 6 99]  c=[0 0 0 0 0 1 2 3 4 5 6 99 0 0 0 0 0 0 0 99]

Enter fullscreen mode Exit fullscreen mode

  • b starts at length 5, then 7 elements appended → length 12, capacity doubles: 5 → 10 → 20.
  • b[19] panics — index 19 exceeds len(b)-1 (11).
  • c := b[:20] is valid because 20 ≤ cap(b). c shares the same backing array as b.
  • Mutating c[11] also changes b[11] — same backing array.
  • Mutating c[19] does NOT show on b — index 19 is beyond len(b).

Slice #3

Clinical test for re-slicing!

func main() {
    x := []int{1, 2}
    fmt.Println(x[2:])
    x = append(x, 3)
    fmt.Println(x[:4])
}

Enter fullscreen mode Exit fullscreen mode

Question

Will it panic? If yes, which line? If not, what is the result?

Answer

No panic.

  • Line 3 → [] (valid: 2 <= len(x))
  • Line 5 → [1 2 3 0] (valid: 4 <= cap(x) after append)

Slice expressions satisfy 0 <= low <= high <= cap(arr), not just len.

Reference: https://go.dev/ref/spec#Slice_expressions


Pointer #1

type A struct { Name string; Age int }
type B struct { Name *string; Age *int }

var a = []A{{"john", 18}, {"danny", 19}, {"carl", 20}}

func main() {
    var b []B
    for _, v := range a {
        b = append(b, B{Name: &v.Name, Age: &v.Age})
    }
    for _, v := range b {
        fmt.Println(*v.Name, *v.Age)
    }
}

Enter fullscreen mode Exit fullscreen mode

Question

What is the expected output of the second loop?

Answer
carl 20
carl 20
carl 20

Enter fullscreen mode Exit fullscreen mode

The loop variable v is reused each iteration — its address is identical every time. All entries in b point to the same address, which holds the last value.

Fix: reference the original slice element by index.

for i := range a {
    b = append(b, B{Name: &a[i].Name, Age: &a[i].Age})
}

Enter fullscreen mode Exit fullscreen mode



Pointer #2

func main() {
    var a *int
    *a = 111
    fmt.Println(*a)
}

Enter fullscreen mode Exit fullscreen mode

Question

What is the expected output?

Answer

Panica is nil. Dereferencing a nil pointer causes a runtime panic.

func main() {
    var a *int
    b := 1
    a = &b
    *a = 111
    fmt.Println(*a) // 111
}

Enter fullscreen mode Exit fullscreen mode



Struct #1 (and Pointer)

type counter struct{ I int }

func (d *counter) inc() { d.I++ }
func NewCounter(in int) *counter { return &counter{I: in} }
func A(d counter) { d.inc() }
func B(d *counter) { d.inc() }

func main() {
    c := NewCounter(0)
    fmt.Println("start", c.I)
    A(*c); A(*c); A(*c)
    fmt.Println("result from A is", c.I)
    B(c); B(c); B(c)
    fmt.Println("result from B is", c.I)
}

Enter fullscreen mode Exit fullscreen mode

Question

What is the expected output?

Answer
start 0
result from A is 0
result from B is 3

Enter fullscreen mode Exit fullscreen mode

A receives a copy — mutations don't affect the original.
B receives a pointer — mutations affect the original.


Struct #2 (and Interface)

type counter struct{ I int }

func (d counter) inc() { d.I++ }
func NewCounter(in int) *counter { return &counter{I: in} }

type ICounter interface{ inc() }
func dofunc(d ICounter) { d.inc() }

func main() {
    c := NewCounter(0)
    fmt.Println("start", c.I)
    dofunc(*c); dofunc(*c)
    fmt.Println("result from A is", c.I)
    dofunc(c); dofunc(c)
    fmt.Println("result from B is", c.I)
}

Enter fullscreen mode Exit fullscreen mode

Question

Can we pass either struct or pointer-to-struct to dofunc? What is the output?

Answer

Yes, both compile — but the result is always 0. inc is a value receiver, so every call gets a copy.

start 0
result from A is 0
result from B is 0

Enter fullscreen mode Exit fullscreen mode

Fix: change inc to a pointer receiver func (d *counter) inc() and pass only the pointer.

Reference: https://stackoverflow.com/questions/44370277/type-is-pointer-to-interface-not-interface-confusion



Decimal

func main() {
    v1 := decimal.NewFromInt(100)
    var v2 decimal.Decimal
    if v2 != decimal.Zero {           // line 4
        fmt.Println(v1.Div(v2))
    }
    if v2.Cmp(decimal.Zero) != 0 {   // line 8
        fmt.Println(v1.Div(v2))
    }
}

Enter fullscreen mode Exit fullscreen mode

Question

Between line 4 and line 8, which properly prevents dividing by zero?

Answer

Line 8 — using .Cmp().

decimal.Decimal is a struct. Using != compares field-by-field and can give unexpected results. Always use .Cmp(decimal.Zero) != 0 to compare decimal values correctly.