Curried functions in Rust and lifetimes

Hello, I’m trying to make this following curried function:

    pub fn read_file_error(file: &str) -> impl Fn(String) -> Result<(), I18nError> {
        move |_| {
            let error = format!("Cannot read file {}", file);
            Err(I18nError::new(error))
        }
    }

However, I get this error:

pub fn read_file_error(file: &str) -> impl Fn(String) -> Result<(), I18nError> {
|                                         ---------------------------------------- this return type evaluates to the `'static` lifetime...
30 | /     move |_| {
31 | |         let error = format!("Cannot read file {}", file);
32 | |         Err(I18nError::new(error))
33 | |     }
| |_____^ ...but this borrow...
|
note: ...can't outlive the anonymous lifetime #1 defined on the function body at 29:1
--> src/error.rs:29:1
|
29 | / pub fn read_file_error(file: &str) -> impl Fn(String) -> Result<(), I18nError> {
30 | |     move |_| {
31 | |         let error = format!("Cannot read file {}", file);
32 | |         Err(I18nError::new(error))
33 | |     }
34 | | }
| |_^

I’m not to sure how to resolve this, can anyone help please? Thanks in advance!

 pub fn read_file_error<'a>(file: &'a str) -> impl 'a + Fn(String) -> Result<(), I18nError> {
    move |_| {
        let error = format!("Cannot read file {}", file); Err(I18nError::new(error))
    }
} 
2 Likes

Or, if like me you try to avoid named lifetimes,

pub fn read_file_error(file: &str) -> impl '_ + Fn(String) -> Result<(), I18nError> {
    move |_| {
        let error = format!("Cannot read file {}", file);
        Err(I18nError::new(error))
    }
}

https://play.rust-lang.org/?edition=2018&gist=ae6d795004f6d965147dd0f08bb49206

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.