Passing LazyLock into generic functions (AsRef, Into)
⚓ Rust 📅 2025-07-19 👤 surdeus 👁️ 20Hi folks,
Recently I played with LazyLock to cache a custom struct with values that can't be const/static and I found that I can't pass LazyLock into a function that uses AsRef<mystruct> instead of simply &mystruct.
(in the example I simply use String instead of a custom struct)
use std::sync::LazyLock;
static CACHED_VALUE: LazyLock<String> = LazyLock::new(|| "This is the cached value".to_owned());
pub fn try_this() {
let value_not_cached = String::from("abc");
print_length(value_not_cached); // works ok
print_length(CACHED_VALUE); // the trait bound LazyLock<std::string::String>: AsRef<str> is not satisfied the trait AsRef<str> is not implemented for LazyLock<std::string::String
}
// stupid example of a function that takes AsRef
pub fn print_length<S>(str: S)
where
S: AsRef<str>,
{
let number = str.as_ref().len();
println!("length is: {number}")
}
This makes sense but I wonder, is there a solution without re-writing functions like print_length that take AsRef<mystruct> or Into<mystruct>.
Thank you.
1 post - 1 participant
🏷️ rust_feed