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

推荐订阅源

Forbes - Security
Forbes - Security
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
L
LangChain Blog
量子位
GbyAI
GbyAI
B
Blog RSS Feed
月光博客
月光博客
人人都是产品经理
人人都是产品经理
腾讯CDC
Recent Announcements
Recent Announcements
Microsoft Azure Blog
Microsoft Azure Blog
I
InfoQ
The Cloudflare Blog
D
Docker
Cyberwarzone
Cyberwarzone
U
Unit 42
NISL@THU
NISL@THU
C
Check Point Blog
B
Blog
大猫的无限游戏
大猫的无限游戏
Cisco Talos Blog
Cisco Talos Blog
Recorded Future
Recorded Future
H
Hackread – Cybersecurity News, Data Breaches, AI and More
J
Java Code Geeks
G
GRAHAM CLULEY
Engineering at Meta
Engineering at Meta
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园 - 叶小钗
P
Proofpoint News Feed
F
Fortinet All Blogs
V
V2EX
T
Threat Research - Cisco Blogs
T
Threatpost
S
SegmentFault 最新的问题
Know Your Adversary
Know Your Adversary
雷峰网
雷峰网
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
博客园 - 司徒正美
P
Privacy & Cybersecurity Law Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
TaoSecurity Blog
TaoSecurity Blog
Latest news
Latest news
Apple Machine Learning Research
Apple Machine Learning Research
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Y
Y Combinator Blog
P
Privacy International News Feed
L
Lohrmann on Cybersecurity
AWS News Blog
AWS News Blog
G
Google Developers Blog
美团技术团队

The Rust Programming Language Forum - Latest topics

Beginner building a Rust backend framework (AI-assisted) — feedback appreciated C++ to Rust -- Exceptions Re-exporting a trait with a custom derive_macro Gold linker is deprecated Why is using PhantomData valid in this case? Code review for Static Pool Allocator Looking for a pool based allocator Why is this legal? What does it mean for Rustc to run "out of TLS keys"? Using async/await internally with no internal runtime, but exposing a nonblocking poll API — is this a reasonable design? Testing functions that use randomness `cargo-path`: improve coding agents&#39; ability to find Rust documentation Rust task runners Lifetime weird case Windows - USB device not detected A random rustc-ice-[...].txt file appeared Develop rust where the environment is setup in a docker Undefined Behavior: in-bounds pointer arithmetic failed: attempting to offset pointer by 20 bytes, but got alloc238 which is only 1 byte from the end of the allocation Unbug 0.5 - Runtime debug assertions Is there a tiny error in section 6.2 Reference types? Lifetime woes implementing ratatui::Widget for a reference Rusqlite + Chrono: How do I simplify code to obtain chrono datetime value From OOP to Rust – struggling with code organization and data structure design Way to avoid a self-referential struct Rust RF and audio resources/communities Whyhttp - HTTP mocks that fail where the bug actually is Using tokio channel permits in a tower service Arc::increment_strong_count design question (cross-post) `&T`, `&mut T`, `Pin<&mut T>` and `&Cell<T>`: Ways of Borrowing a `T` Ratatui detect arrow key press and release Feedback about post in medium Debugger not showing/offering variables? nestrs: a NestJS-style framework for Rust built on Axum and Tower Confusion about struct variance with &mut dyn Narwhal v0.6.0 – message broker for edge apps, now with channel persistence Quiche client sent message not received at the server side "mysql" "Packets out of sync" - workaround Consistency f64 and std::Simd<f64, N> Signal semantics for Rust Snowflake-gen 1.0 - Configurable Snowflake ID generator with thread-local global API How do I do hmr in rust Diving into Rust: My Journey So Far and a Few Hiccups Celerity 0.1.1: pure Rust ZMTP 3.1 with a sans-IO core, Tokio transport, and CURVE-RS How to call struct method as function pointer in loop Loops inside loops and mutable reference on Iterator VSCode - rust-analyzer - annoying re-builds due to RUSTC_BOOTSTRAP changed Borsh v1.6.1 example What's everyone working on this week (17/2026)? Cargo test's verbose output - can I quiet it? Sem: semantic entity level version control CLI built with tree-sitter How do i get all the words in a string and convert it into a vector? Looking for feedback on my first tokenizer in Rust Frostmirror - (lightweight airgap alternative inspired from panamax and romt) - an offline cargo repository for airgap system that can be deployed through a docker image Does "ill-formed, no diagnostic required" exist in Rust? If a program is built with software floating-point emulation, is it affected by hardware floating-point environment? Rustc-link-lib static library How does crates.io and docs.rs store crates? Various input in one line error[E0080]: index out of bounds error when trying to install LuaCAD CSV to SQLite - Is it better to write records as they are being read Looking for feedback for a graph-based task scheduler Confusion: struct directly followed by impl? This is my first project. I invented a new algorithm that even AI don't know. It's about bigint. And I'm 15. Thanks for watching. By the way, my crate named `nna` Why Windows rustc uses a different color scheme? Associate a struct with every enum variant Which Windows env var is responsible for DNS resolition? Clap completion question Is RMW operation less prone to reading stale values than a pure load? Crates with excluded proprietary parts Why are builds of my crate's test not consistent (cargo build vs cargo test vs VSCode-Test-Explorer) Why there is no downcast method Type inference of generic parameters How to make Rust as vertical as possible? Cyw43 on STM32H723 Typing is fun! Another crate for self-referential structs How to use build-analysis feature? Why can't I upgrade a known-exclusive &T to &mut T? Issues with Boxed trait objects Rust-analyzer Language Server LoMux: Adobe Media Encoder Alternative (First Rust Project) Cbor-core: A deterministic CBOR::Core encoder/decoder Numa - a DNS resolver from scratch How should I deal with copying and renaming in monitoring of files? Request get to api.github.com Compiler Preprocessing Optimization Lifetime trait bounds issue High-Performance API Gateway Implemented a Rust-based CLI tool that supports Ollama's local LLMs Egui_tracing 0.3 — a live tracing/log viewer widget for egui apps Elevation-kit capstone project Panic-free-friendly standard library Work around library with private trait in public trait bound My custom Tab implementation with Slint How to express this complex struct definition which uses closures and multiple layers of higher-ranked lifetimes in Rust? 30K lines of no_std Rust: a bare-metal ARM64 hypervisor that replaces Google's Hafnium SPMC Imperartive or functional? Any improvements? Loop unrolling in manually written loops vs iterators (AVX512) Announcing cachekit 0.7 — pluggable cache policies and arena-backed primitives Need some suggestions Having Multiple Mutable References via Iterators
Loops with accumulated state confuse me
RobertN · 2026-04-16 · via The Rust Programming Language Forum - Latest topics

While @jdahlstrom’s solution is a really elegant one, I would like to point out a more general perspective.

This is the first half of the problem, and the simpler one.

Basically, this is a nested sequence: a sequence of sequences, an array of arrays, two nested loops, or a generator function returning generators. There are many manifestations of this concept.

They all share the idea of flattening: somewhere in the program, you only see the inner item. In your example, that is the body of the nested for loop. That is one of many possible solutions, and it is perfectly fine.

This is the second half of the problem.

“When it changes” means that you are effectively processing the sequence in pairs. There is some function or logic that takes two elements from the (abstract) sequence as parameters.

And at the end, your implicit requirement is that this function or logic should still be called with the last element of the sequence as the first parameter, even though there is obviously no element available for the second parameter. That missing thing is the root cause of the awkward repeated if statement in your example.

A very old technique, with its origins, I think, in list processing, is the introduction of sentinel values at the end (and sometimes the beginning) of a sequence. These values can be concrete instances of the original element type, or special values.

An extremely widely adopted sentinel value, for example, is the terminating NULL byte in strings in many programming languages. It is so common that virtually nobody realizes that the NULL is a sentinel. :wink:

In a language like Rust, you can define better sentinel values by using enums, or simply use a pre-made enum like Option. So, given a (flattened) sequence, you add sentinels and then process it.

A more general example:

fn main() {
    let sequence = [1, 2, 3];
    let iter = sequence.iter().map(Some).chain([None]);
    let mut last = None;
    for item in iter {
        match (last, item) {
            (None, Some(x)) => println!("first: {x}"),
            (Some(a), Some(b)) => println!("pair: ({a}, {b})"),
            (Some(x), None) => println!("last: {x}"),
            _ => unreachable!(),
        }
        last = item;
    }
}

And more concretely for your example (note: your original code processed an empty buffer at the start; this one does not):

fn process_buffer(buf: &mut Vec<char>) {
    println!("process_buffer: {buf:?}");
    buf.clear();
}

fn char_language(c: char) -> u32 {
    c as u32
}

fn main() {
    let strs = ["aab", "bbc", "dda"];
    let chars = strs.iter().flat_map(|s| s.chars());
    let mut buf = Vec::new();
    let mut prev_lang = None;
    for c in chars.map(Some).chain([None]) {
        let lang = c.map(char_language);
        if lang != prev_lang && prev_lang.is_some() {
            process_buffer(&mut buf);
        }
        if let Some(c) = c {
            buf.push(c);
        }
        prev_lang = lang;
    }
    assert!(buf.is_empty());
}

The concept of sentinels can be generalized even further. Different sentinel-like values can be inserted into a sequence at different points to carry information forward to subsequent operations on that sequence.