[ISSUE] Trouble expressing lifetime-coupled return types with fn(&[u8]) -> T in generic context

⚓ Rust    📅 2025-07-31    👤 surdeus    👁️ 11      

surdeus

Warning

This post was published 125 days ago. The information described in this article may have changed.

I've labeled this as an issue since I'm pretty sure there isn't a mistake on my end, though this problem might be known already, and worked on, by the Rust team. In any case, the compiler doesn't give me enough descriptive hints to go on.
I've simplified my code as much as I can. Here's the scenario:

A Converter is a function which takes a slice of bytes and returns a value of a type that is to be specified later, but it must implement Debug. Aside from that, I want to express that this return value must also be bound by the same lifetime as the input. Something along the lines of this:

type Converter<'a, T: 'a + Debug> = fn(&'a [u8]) -> T;

This compiles, but when I try to use it like below, it doesn't.

A MAP is a closure which returns a corresponding Converter based on a given Locale, or None if it does not have one.

I've attempted:

pub fn formatWithConverter<'strings, SHOW, MAP>(
    unconvertedStrings : &'strings Vec<Vec<u8>>,
    fmt                : &mut fmt::Formatter<'_>,
    converter          : MAP,
) -> fmt::Result
where
    SHOW : Debug,
    MAP  : Fn(Locale) -> Option<for <'x> Converter<'x, SHOW>>,
{
    // print the strings that can be converted
    ...
}

but this does not compile, which makes sense, since there is nothing to couple SHOW to 'x. However:

pub fn formatWithConverter<'strings, SHOW, MAP>(
    unconvertedStrings : &'strings Vec<Vec<u8>>,
    fmt                : &mut fmt::Formatter<'_>,
    converter          : MAP,
) -> fmt::Result
where
    SHOW : 'strings + Debug,
    MAP  : Fn(Locale) -> Option<Converter<'strings, SHOW>>,
{
    ...
}

does not compile once I actually call formatWithConverter.
Simply ignoring the lifetimes associated with the Converter alltogether, like so:

pub fn formatWithConverter<'strings, SHOW, MAP>(
    unconvertedStrings : &'strings Vec<Vec<u8>>,
    fmt                : &mut fmt::Formatter<'_>,
    converter          : MAP,
) -> fmt::Result
where
    SHOW : Debug,
    MAP  : Fn(Locale) -> Option<fn(&[byte])->SHOW>,
{
    ...
}

does not compile once I actually use a fn(&'a [byte])->&'a str as a Converter, but it does compile for fn(&'a [byte]) -> String.

2 posts - 2 participants

Read full topic

🏷️ Rust_feed