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

推荐订阅源

V
V2EX
Cisco Talos Blog
Cisco Talos Blog
MongoDB | Blog
MongoDB | Blog
IT之家
IT之家
N
News and Events Feed by Topic
博客园 - 叶小钗
Help Net Security
Help Net Security
美团技术团队
Attack and Defense Labs
Attack and Defense Labs
雷峰网
雷峰网
S
Security @ Cisco Blogs
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
WordPress大学
WordPress大学
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
AI
AI
Hacker News: Ask HN
Hacker News: Ask HN
T
The Blog of Author Tim Ferriss
Security Latest
Security Latest
Last Week in AI
Last Week in AI
S
Secure Thoughts
Simon Willison's Weblog
Simon Willison's Weblog
TaoSecurity Blog
TaoSecurity Blog
N
News and Events Feed by Topic
A
Arctic Wolf
Y
Y Combinator Blog
MyScale Blog
MyScale Blog
Cyberwarzone
Cyberwarzone
酷 壳 – CoolShell
酷 壳 – CoolShell
S
SegmentFault 最新的问题
罗磊的独立博客
Vercel News
Vercel News
D
DataBreaches.Net
博客园 - 聂微东
P
Palo Alto Networks Blog
N
News | PayPal Newsroom
GbyAI
GbyAI
B
Blog
A
About on SuperTechFans
PCI Perspectives
PCI Perspectives
S
Schneier on Security
Apple Machine Learning Research
Apple Machine Learning Research
I
InfoQ
The GitHub Blog
The GitHub Blog
P
Privacy International News Feed
Blog — PlanetScale
Blog — PlanetScale
博客园_首页
T
The Exploit Database - CXSecurity.com
V
Vulnerabilities – Threatpost
aimingoo的专栏
aimingoo的专栏
Google DeepMind News
Google DeepMind News

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
Unions: delving into unsafe Rust
Mila K · 2026-05-06 · via DEV Community

I came across union while looking through the code of the client's library for the new trading platform WATS by the Warsaw Stock Exchange (GPW), which currently is (still) under development.

When I skimmed through the code, I noticed a lot of unsafe functions, that were the artifacts of using unions instead of structures or enums.

I never used or even encountered the unions before, so I wanted to learn about them. It proved to be an interesting journey, where I also revisited other Rust topics (like memory safety and ownership).

According to official documentation, union uses the same syntax as structure.

If I would describe it unofficially: it's like a child between struct and enum - it looks like structure, but behaves more like enum - but is neither of them.

struct FooStruct {
   x: i64,
   y: f64
}

union FooUnion {  // <---- union instead of struct
   x: i64,
   y: f64
}

Enter fullscreen mode Exit fullscreen mode

In the code snippet above, we declare FooStruct, which is a structure with 2 fields: x for the integer value, and y for the float.
The FooUnion has identical fields, from reading the code, but under the hood, union can store only 1 value! Which value? Compiler does not know, this is why reading the value should be enclosed into unsafe block or function.
While Rust is generally very descriptive about value's mutability, here, actually, the writing to the field is safe. This is because we have only one place to write to, so as long as the variable has a mutable ownership of the value, it can be overwritten.

let mut my_union = FooUnion { y: 23.5 };
my_union.y = 25.7;

Enter fullscreen mode Exit fullscreen mode

With union, what we're saying to the compiler is: FooUnion will store either integer or float in the single memory allocation, look away when we access it, as WE know how to handle it.
Thus, to declare it, we'll use:

let my_struct = FooStruct { x: 42, y: 23.5 };

// Union declares only one of its fields
let my_union = FooUnion { x: 42 };

Enter fullscreen mode Exit fullscreen mode

This instantly reminds me of the enum - (remove the unsafe part) - there is only one value currently stored.

The natural train of my thoughts was: what about pattern matching? The Rust documentation conveniently provides the match statement:

let u = FooUnion { x: 10 };

unsafe {
    match u {
        FooUnion { x: 10 } => println!("Found exactly ten!"),
        FooUnion { y } => println!("Found y = {y} !"),
    }
}

Enter fullscreen mode Exit fullscreen mode

However, if we rewrite the match into a statement used in an enum, we'll see a warning that the second arm is unreachable.

unsafe {
    match u {
        FooUnion { x } => println!("Found x = {x} !"),
        FooUnion { y } => println!("Found y = {y} !"), , // <-|
 //                           warning: unreachable pattern  --|
    }
}
// Alternatively, we can use std::mem::transmute to transform value
// unsafe{
//     let val = std::mem::transmute::<FooUnion, i32>(my_union);
//     println!("Found value = {val} !");
// }

Enter fullscreen mode Exit fullscreen mode

(「•-•)「 ʷʱʸ? Because there is nothing to compare, we don't have a few variants to match against: we have 1 union with 1 field, whatever we'll write in the initialisation call.

let u = FooUnion { x: 10 };

// OR
let u = FooUnion { y: 23.5 };

Enter fullscreen mode Exit fullscreen mode

The result from the match statement will be Found x = 10 ! if the value was "under" x, or we'll have Found x = 1102839808 ! (which is a 23.5 representation of the float value in Big Endian type) - which probably means nothing during run time.

Let's add the field that stores values on the Heap. The most obvious one is a String. If we include it into the fields of the union, it requires us to add std::mem::ManuallyDrop wrapper - which is a neat reminder that we need to drop the variable ourselves.

Accessing value (≖_≖ )

How do you know what is a stored value? I found myself accustomed to writing if statements that guarantee that the type is known, like if let Variant::A = var { ... }, however, I could not understand how to do it with union.
Apparently, you cannot: this is a real definition of unsafety.
This code would produce different outputs: first one is the length of the string, another one - is an actual string. In this case, compiler cannot help us to write the matching arms, it expects from us to KNOW the type that is stored under the variable.

pub union FooUnionHeap {
    x: i32,
    y: f32,
    z: std::mem::ManuallyDrop<String>,
}

let s = "HelloWorld".to_string();
let my_union_h = FooUnionHeap { z: ManuallyDrop::new(s) };


unsafe {
    match my_union_h {
        FooUnionHeap { x } => { println!("Found x = {x} !"); },

    };
}

// Output: `Found x = 10 !`

unsafe {
    match my_union_h {
        FooUnionHeap { z } => { 
            println!("Found z = {} !", z.to_string()) 
        },

    };
}

// Output: `Found z = HelloWorld !`

Enter fullscreen mode Exit fullscreen mode

The same goes for just borrowing different fields:

let my_union = FooUnion { y: 25.7 };
unsafe {
    let a = &my_union.x;
    let b = &my_union.y;
    println!("a: {a}, b: {b}");
}
// Output: `a: 1103993242, b: 25.7`.

Enter fullscreen mode Exit fullscreen mode

Size of the type (>.<)人(⸝⸝⸝>﹏<⸝⸝⸝)

The size of structure and union is different, because structure's size is roughly the sum of its fields (+ alignment), and for union - size of its largest field. However, the union has the same size in bytes as enum. Even after comparing both against the union with C representation (which can change the padding between fields), the size is the same.

pub struct FooStruct {
    x: i32,
    z: String,
}

pub enum FooEnum {
    X(i32),
    Z(String)
}

#[repr(C, packed)]
pub union FooUnionHeapC {
    pub x: i32,
    pub z: ManuallyDrop<String>,
}

pub union FooUnionHeap {
    x: i32,
    z: ManuallyDrop<String>,
}
println!("Size of heap allocated union: {}",
    std::mem::size_of::<FooUnionHeap>());
// Output: Size of heap allocated union: 24
println!("Size of heap allocated union with C representation: {}",
    std::mem::size_of::<FooUnionHeap>());
// Output: Size of heap allocated union with C representation: 24
println!("Size of enum: {}", std::mem::size_of::<FooEnum>());
// Output: Size of enum: 24
println!("Size of structure: {}", std::mem::size_of::<FooStruct>());
// Output: Size of structure: 32

Enter fullscreen mode Exit fullscreen mode

Speed 三三ᕕ( ᐛ )ᕗ

Here, we compare only the enum and union using criterion tool.

Both creation and access of the union is faster - probably because both creation and access to the enum requires also to check the discriminant, which holds information about used variant.

Creation time comparison

Access time comparison

The DANGER ( ꩜ ᯅ ꩜;)

With great power comes great responsibility --- Amazing Fantasy, and more specifically
It is the programmer’s responsibility to make sure that the data is valid at the field’s type --- The Rust Reference

To see how everything compiles, but panics during runtime, we must manually drop the value first, and then access it to read.

// Drops the `z` field from the union
fn consume(u: &mut FooUnionHeap) {
    unsafe{ ManuallyDrop::drop(&mut u.z); }
}


fn outer() {
    let s = "HelloWorld".to_string();
    // owner of the union
    let mut my_union_h = FooUnionHeap { z: ManuallyDrop::new(s) };

    // union's `z` field is dropped here
    consume(&mut my_union_h);

    // reading the `z` field
    unsafe {
        match &my_union_h {
            FooUnionHeap { z } => { 
                println!("Found z = {} !", z.to_string()) 
            },
        }
    };
}

// The ERROR: unsafe precondition(s) violated:
// ptr::copy_nonoverlapping requires that both pointer arguments are
// aligned and non-null and the specified memory 
// ranges do not overlap

// This indicates a bug in the program. 
// This Undefined Behavior check is optional, and 
// cannot be relied on for safety.

Enter fullscreen mode Exit fullscreen mode

The compiler looked away while we crashed due to the dangling pointers.

Why and when to use them? ᕙ(⇀‸↼‶)ᕗ

When unions were first introduced in Rust in 2015, the goal was to provide the native support for C-compatible unions (RFC).

For me, if not in FFI, they are the thieves of joy developing in Rust - you must know what to use when, and be sure it exists - manageable in small code bases, nightmare - in large.

Why it was chosen in WATS - I think speed or/and compatibility with some C API. After all, it is a trading platform.

The code is available on Github.

What do you think? (☞ ͡° ͜ʖ ͡°)☞