This repository has been archived on 2020-09-15. You can view files and clone it, but cannot push or open issues or pull requests.
Files
not-python-old.2020-08-27/src/util.rs

39 lines
771 B
Rust
Raw Normal View History

use std::{
fmt::{Display, Formatter, self},
};
pub struct LazyString<'f, F>
where F: Fn() -> String + 'f
{
source: F,
_lifetime: std::marker::PhantomData<dyn Fn() + 'f>,
}
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");
}