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

推荐订阅源

www.infosecurity-magazine.com
www.infosecurity-magazine.com
D
DataBreaches.Net
T
Tailwind CSS Blog
M
MIT News - Artificial intelligence
Stack Overflow Blog
Stack Overflow Blog
F
Full Disclosure
V2EX - 技术
V2EX - 技术
N
News and Events Feed by Topic
Help Net Security
Help Net Security
L
LangChain Blog
Y
Y Combinator Blog
宝玉的分享
宝玉的分享
Google Online Security Blog
Google Online Security Blog
P
Proofpoint News Feed
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
T
The Blog of Author Tim Ferriss
Google DeepMind News
Google DeepMind News
The Register - Security
The Register - Security
B
Blog RSS Feed
N
Netflix TechBlog - Medium
N
News | PayPal Newsroom
TaoSecurity Blog
TaoSecurity Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
V
Vulnerabilities – Threatpost
B
Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
I
Intezer
H
Hackread – Cybersecurity News, Data Breaches, AI and More
博客园_首页
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
AI
AI
aimingoo的专栏
aimingoo的专栏
大猫的无限游戏
大猫的无限游戏
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Cyberwarzone
Cyberwarzone
P
Proofpoint News Feed
Google DeepMind News
Google DeepMind News
G
GRAHAM CLULEY
Vercel News
Vercel News
罗磊的独立博客
MyScale Blog
MyScale Blog
Last Week in AI
Last Week in AI
博客园 - 司徒正美
C
CERT Recently Published Vulnerability Notes
GbyAI
GbyAI
Scott Helme
Scott Helme
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
T
Troy Hunt's Blog
A
About on SuperTechFans
P
Privacy International News Feed

The Rust Programming Language Forum - Latest posts

What's everyone working on this week (21/2026)? Rust Function Call with one Param Iced + Canvas + Text: How do I create a style for canvas text "Value dropped while borrowed" as a lifetime mismatch Weird `use of moved value` behaviour Slightly surprising behavior of a while loop Clap: how to disable options after a certain positional argument How do i tell rust-analyzer what kind of bracket to use for a macro? Iterator + Borrow Checker: Work around borrowing already borrowed mutable variable Requesting data via mavlink SKILLS.md for Rust development 🧵 Stringlet UTF-8 Hack Option Niche? Iterator + Map - How do divide every element, including the last element, by the last element Why can't we store returned value of a function in a variable if one of the parameters goes out of scope My first crate :D, floop: A more convenient and less error prone replacement for loop `{ select! { .. }}` Sorting is slow because architectures are wrong — zan-sort redesigns the architecture, not the algorithm Iced Font - Create a custom monospace font to display dollar amounts Is the UnsafePinned RFC wrong about being able to return `&mut T` from `get_mut_unchecked`? Fixing Polars 0.37 compilation errors: Hashbrown 0.17 dependency conflict and decimal parsing Any plans for improving error diagnostic in Rust 2.0? How do I build completely offline? Is `&mut T -> &mut ManuallyDrop<T>` well-defined and sound? Would you use this? — fixtura, declarative fake data injection for tests Foreign trait restrictions on native types make generics hard to use Cargo Exclude Directive Compiler reasoning around a modulo counter Multiple mutable references to elements within one vector Handling non-`Send` data in a `Send` closure Review: Static Multi Pool Allocator Rmquickjs - High-level MicroQuickJS bindings for Rust Iced + Rusqlite + Chrono: Problem with custom error type Why can&#39;t the Rust compiler infer the T type parameter in this BTreeMap::range call? 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 Discussion on Synchronous Crate Concurrency Refactor using Stackful Coroutines Model in Rust Can a future used only by `async fn` assume it won&#39;t be polled again after becoming ready? High-performance `fast-powi` crate 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? Vasya go to (his) Home 🏡 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 How do I do hmr in rust 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 (14/2026)? What's everyone working on this week (17/2026)? RawWakerVTable functions, did I write them correctly? 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? Basic Object Oriented Programming in Rust 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 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? Clap completion question Is RMW operation less prone to reading stale values than a pure load? Why are builds of my crate's test not consistent (cargo build vs cargo test vs VSCode-Test-Explorer) Cyw43 on STM32H723 Reducing code repetition with Vecs and fields Are there any object detection libraries out there for the Arduino?
Type inference of generic parameters
luma98002 · 2026-04-17 · via The Rust Programming Language Forum - Latest posts

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 ...) ↩︎