Difference between `|s| LeanString::from(s)` and `LeanString::from`

⚓ Rust    📅 2026-03-22    👤 surdeus    👁️ 3      

surdeus

Please help me understand why |s| LeanString::from(s) works, but LeanString::from does not. What's the difference between them?

See the code inside fn visit_str() below.

#![feature(hash_set_entry)]

use std::{cell::RefCell, collections::HashSet};

use lean_string::LeanString;
use serde::de::{Error, Visitor};

thread_local! {
    static STRING_POOL: RefCell<HashSet<LeanString>> = <_>::default();
}

struct StringVisitor;

impl<'de> Visitor<'de> for StringVisitor {
    type Value = LeanString;

    fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
        formatter.write_str("a string")
    }

    fn visit_str<E>(self, buffer: &str) -> Result<Self::Value, E>
    where
        E: Error,
    {
        STRING_POOL.with_borrow_mut(|pool| {
            // Ok(pool.get_or_insert_with(buffer, |s| LeanString::from(s)).clone())
            Ok(pool.get_or_insert_with(buffer, LeanString::from).clone())
        })
    }
}
[dependencies]
lean_string = "0.5.3"
serde = "1.0.228"

Here's the compilation error. I don't understand what is meant by "some specific lifetime '2". Is "some specific lifetime" different from "any lifetime"?

error: implementation of `FnOnce` is not general enough
   ╭▸ src/main.rs:29:16
   │
29 │             Ok(pool.get_or_insert_with(buffer, LeanString::from).clone())
   │                ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ implementation of `FnOnce` is not general enough
   │
   ├ note: `fn(&'2 str) -> LeanString {<LeanString as From<&'2 str>>::from}` must implement `FnOnce<(&'1 str,)>`, for any lifetime `'1`...
   ╰ note: ...but it actually implements `FnOnce<(&'2 str,)>`, for some specific lifetime `'2`

6 posts - 4 participants

Read full topic

🏷️ Rust_feed