use std::{ fmt::{Display, Formatter, self}, }; pub struct LazyString<'f, F> where F: Fn() -> String + 'f { source: F, _lifetime: std::marker::PhantomData, } impl<'f, F> LazyString<'f, F> where F: Fn() -> String + 'f { pub fn new(source: F) -> Self { LazyString { source, _lifetime: Default::default(), } } } impl<'f, F> Display for LazyString<'f, F> where F: Fn() -> String + 'f { fn fmt(&self, fmt: &mut Formatter) -> fmt::Result { let s = (self.source)(); Display::fmt(&s, fmt) } } #[test] fn test_lazy_string() { let i = 10; let lzstr = LazyString::new(|| format!("the value is {}", i)); assert_eq!(lzstr.to_string(), "the value is 10"); }