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

推荐订阅源

G
Google Developers Blog
Jina AI
Jina AI
大猫的无限游戏
大猫的无限游戏
Martin Fowler
Martin Fowler
博客园 - 司徒正美
云风的 BLOG
云风的 BLOG
C
Cybersecurity and Infrastructure Security Agency CISA
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
S
Securelist
S
Security Affairs
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
L
LINUX DO - 热门话题
博客园 - 三生石上(FineUI控件)
T
Threatpost
T
The Blog of Author Tim Ferriss
C
CERT Recently Published Vulnerability Notes
IT之家
IT之家
P
Palo Alto Networks Blog
Microsoft Azure Blog
Microsoft Azure Blog
Spread Privacy
Spread Privacy
Cyberwarzone
Cyberwarzone
腾讯CDC
L
LangChain Blog
Know Your Adversary
Know Your Adversary
C
CXSECURITY Database RSS Feed - CXSecurity.com
GbyAI
GbyAI
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
I
Intezer
T
Tor Project blog
AWS News Blog
AWS News Blog
T
Tenable Blog
NISL@THU
NISL@THU
Security Latest
Security Latest
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
H
Hackread – Cybersecurity News, Data Breaches, AI and More
人人都是产品经理
人人都是产品经理
MongoDB | Blog
MongoDB | Blog
MyScale Blog
MyScale Blog
D
DataBreaches.Net
Microsoft Security Blog
Microsoft Security Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
量子位
美团技术团队
The Cloudflare Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
罗磊的独立博客
The GitHub Blog
The GitHub Blog
阮一峰的网络日志
阮一峰的网络日志
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Stack Overflow Blog
Stack Overflow 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 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 Loops with accumulated state confuse me 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
Type inference of generic parameters
luma98002 · 2026-04-17 · via The Rust Programming Language Forum - Latest topics

It's not so much "the compiler chose not to dig through function bodies" so much as "digging through function bodies doesn't make sense here". The function body does not have a say in what the generic parameter ends up being. The caller decides that.

You were passing a specific type, a &Path, to the closure within the function body. That's a "choice" the function body made. The caller has no say in that, so it didn't make sense for the closure argument to be represented by a generic.

The closure was a solution to a follow-up problem (which was not an inference problem), and not the original (inference) problem. By that point I had removed the S parameter from find_matches.

It's still instructive, so I'll work through it. But it's not a problem about inference, so it's somewhat off-topic.

Anyway, let's start from here. The problem is that F: Fn(&Path, &parser::Grep) -> io::Result<()> means that there must be a single type F which implements Fn(&'lt Path, ...) for all lifetimes 'lt. But the notional implementation of Fn by find_match_in_file<S> cannot meet that bound. The notional implementation looks something like this:

// (Simplified for the sake of presentation, lmk if you want playground code)
impl<'grep, S: AsRef<Path>> Fn(S, &'grep parser::Grep) for find_match_in_file<S> {
    type Output = io::Result<()>;
    fn call(&self, path: S, _args: &'grep parser::Grep) -> Self::Output {
        ...
    }
}

You're trying to pass a &Path, and the bounds that are satisfied by the function are

find_match_in_file<&'a Path>: for<'x> Fn(&'a Path, &'x parser::Grep) -> io::Result<()>
// same thing:
find_match_in_file<&'a Path>: Fn(&'a Path, &parser::Grep) -> io::Result<()>

find_match_in_file<&'b Path>: Fn(&'b Path, &parser::Grep) -> io::Result<()>
find_match_in_file<&'c Path>: Fn(&'c Path, &parser::Grep) -> io::Result<()>
find_match_in_file<&'d Path>: Fn(&'d Path, &parser::Grep) -> io::Result<()>
// ...
find_match_in_file<&'static Path>: Fn(&'static Path, &parser::Grep) -> io::Result<()>

Like Vec<T> and Vec<U> are different types (unless T = U), the function items find_match_in_file<&'a Path> and find_match_in_file<&'b Path> are different types (unless 'a = 'b). So there is no single find_match_in_file<_> type which satisfies the bound on the callback -- no single type which meets the bound on the closure parameter F.

In an impl, if a generic lifetime shows up in the parameters and in the implementing type, then the impl is not creating an implementation that meets a F: Fn(&'_ ...)[1] bound. The lifetime has to show up in the parameters only, and not in the implementing type.

Or in terms of turbofish: it's impossible to write out a find_match_in_file::<X>(...) that can take a &'path Path with any lifetime, it can only take the lifetime in X.

Okay, so that's the problem. Now let's look at the solutions. You asked about the closure solution specifically:

    find_matches(args.recursive, &args.path, &args, |p, g| {
        find_match_in_file(p, g)
    })?;

Here, the closure meets the bound by having an implementation like this:

impl<'path, 'grep> Fn(&'path Path, &'grep parser::Grep) for Closure {
    type Output = io::Result<()>;
    fn call(&self, p: &'path Path, g: &'grep parser::Grep) -> Self::Output {
        // Here within the function body, the lifetimes have been "reified"
        // (to make up a word on the spot) to some concrete lifetimes,
        // similar to how a generic parameter `T` would represent a single
        // type *within* the function body.  (`T` is chosen by the caller.)
        //
        // So there's no requirement for `find_match_in_file` to meet the
        // higher-ranked `F: Fn(&Path, ...)` bound in this context.
        find_match_in_file/* ::<&'path Path> */(p, g)
    }
}

(You could also do this with another function that calls find_match_in_file, it's not closure-specific magic or anything.) Hopefully that explains the fix: the closure handles every possible input lifetime by calling a "different function type" file_match_in_file::<&'path Path> for every lifetime.

And though you didn't ask, the other two fixes work by changing how find_match_in_file<_>'s notional Fn implementations are defined.

// fn find_match_in_file(path: &Path, _args: &parser::Grep) -> io::Result<()>
//
// The function item type is no longer parameterized by a type.
impl<'path, 'grep> Fn(&'path Path, &'grep parser::Grep) for find_match_in_file {
    type Output = io::Result<()>;
    fn call(&self, path: &'path Path, _args: &'grep parser::Grep) -> Self::Output {
        ...
    }
}
// fn find_match_in_file<S>(path: &S, _args: &parser::Grep) -> io::Result<()>
// where S: AsRef<Path> + ?Sized,
//
// Now it's paramertized by a type again, but the lifetime of the `&Path`
// is not part of that type parameter.
impl<
    'path, 
    'grep, 
    S: AsRef<Path> + ?Sized,
> Fn(&'path S, &'grep parser::Grep) for find_match_in_file<S> {
    type Output = io::Result<()>;
    fn call(&self, path: &'path S, _args: &'grep parser::Grep) -> Self::Output {
        ...
    }
}

In both cases, the 'path lifetimes shows up in the parameters, but not in the implementing type.

In terms of turbofish for the generic version, you end up using find_matches_in_file::<Path>, which does not have the 'path lifetime in the <..>.

Finally, why did we need to handle every lifetime in the first place? That is, why doesn't this work.

//              vvvvv
fn find_matches<'path, F, P>(recursive: bool, path: P, args: &parser::Grep, cb: F) -> io::Result<()>
where
    P: AsRef<Path>,
    F: Fn(&'path Path, &parser::Grep) -> io::Result<()>,
    // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

We're only requiring F to work with a single 'path lifetime now, which is compatible with the original find_matches_in_file siguature. But now we get a new error:

error[E0597]: `path_source` does not live long enough
  --> src/main.rs:33:15
   |
27 | fn find_matches<'path, F, P>(recursive: bool, path: P, args: &parser::Grep, cb: F) -> io::Result<()>
   |                 ----- lifetime `'path` defined here
...
32 |     let path_source = PathBuf::new();
   |         ----------- binding `path_source` declared here
33 |     let p = &*path_source;
   |               ^^^^^^^^^^^ borrowed value does not live long enough
...
37 |         match cb(p, args) {
   |               ----------- argument requires that `path_source` is borrowed for `'path`
...
43 | }
   | - `path_source` dropped here while still borrowed

And this final part is a bit more related to the conversation about generic parameters. The caller chooses the 'path lifetime too, and again, the function body has to work with every possible choice that the caller can make -- the function body has no say in how long the lifetime is.

So the caller chould have chosen 'static for example.

In fact, it goes a bit further than that -- it's impossible for the caller to "name" or choose a lifetime that's shorter than the call to find_matches. Within the function body, generic lifetime parameters always represent some borrow duration longer than the function body. So it is never possible to borrow a local variable for as long as a lifetime parameter -- because all locals are moved or dropped by the time we exit the function body.

And we fix this problem by requiring the closure to work with all lifetimes -- including those shorter than the function body.

F: Fn(&Path, &parser::Grep) -> io::Result<()>
// AKA
F: for<'path,'grep> Fn(&'path Path, &'grep parser::Grep) -> io::Result<()>

These for<..>, "for all lifetime" bounds are called higher-ranked trait bounds (HRTBs).

  1. aka F: for<'x> Fn(&'x ...) ↩︎